Mock HTTP responses with custom helpers

In the specs for the RedisWeatherQuery module that we worked with in Chapter 4, Setting Up and Cleaning Up, we mocked HTTP responses to prevent actual requests being sent during test runs. The code that accomplished this was simple:

let(:json_response) { '{}' }

before do
  allow(weather_query).to receive(:http).and_return(json_response)
end

For most specs, we actually don't need any mock response data, so an empty Hash is good enough. But this approach has some problems. First, we may want to validate the response we receive from the API to ensure it meets our expectations of how it is formatted. Second, we may have mocks in our specs that do not look like anything that the API returns. Third, we are treating ...

Get RSpec Essentials now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.