Integration testing with RSpec and RestClient


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.

describe "mocked query of web service" do
it "should perform correct action on system data based on mocked response" do
RestClient = double
file ='RELATIVE_FILE_PATH_HERE', 'r') #Relative to root of Rails app
data =
response = double
response.stub(:code) { 200 }
response.stub(:body) { data }
response.stub(:headers) { {} }
RestClient.stub(:get) { response }
#Your assertions here
view raw gistfile1.txt hosted with ❤ by GitHub



This entry was posted in Uncategorized and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s