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 the response imprecisely, ignoring the HTTP status code, assuming the body is valid JSON, and caching all responses regardless of success or failure status.
All these shortcomings will lead to bugs in our real-world code. Also, debugging will...