I’ve been working on an application that needs to retrieve data from a web service on a regular basis and then update models in my database based on that data.
Ruby has built in support for making HTTP requests but it is quite low level, so I’ve been using the RestClient gem to make things a little easier for myself.
However I needed to be able to test this code, and I needed to make my web services queries deterministic so that I could create assertions based on the results of the processing.
The easiest way I could find to do that was to mock out RestClient with an RSpec mock. Then when the code under test made a query to the web service, the mock would instead return the contents of a file as the web service response. I could then write assertions for the system under test. Here’s the code snippets that make it all work.