Rails : Make test suite with HTTP requests run faster

I was developing a movie sorting ruby application which will fetch data from IMDB database. Unfortunately the gem imdb I have been using to fetch data from IMDB did not have any solution inbuilt to deal with HTTP requests in test mode. My test suite was insanely slow.

Then, I found that the gem imdb uses a gem called fakeweb to fake the HTTP request. fakeweb requires you to know every URL your suite invokes to fake it. Its quite cumbersome, because you may not always figure which URLs the suite is invoking. So, it was a bad idea for me.

Then I thought about the gem vcr which I found to be an awesome tool to record all your HTTP request’s responses as fixtures for the future requests.

require 'rubygems'
require 'test/unit'
require 'vcr'

VCR.configure do |config|
  config.cassette_library_dir = "fixtures/vcr_cassettes"
  config.hook_into :webmock # or :fakeweb
end

class VCRTest < Test::Unit::TestCase
  def test_example_dot_com
    VCR.use_cassette("synopsis") do
      response = Net::HTTP.get_response(URI('http://www.iana.org/domains/reserved'))
      assert_match /Example domains/, response.body
    end
  end
end

Every HTTP request you or your code make inside the code_block passed to `VCR.use_cassette(“synopsis”)` will stubbed with the fixture data if present. If not, it will fetch once and use the same fixture data for future requests.

 

Sources

https://github.com/vcr/vcr

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s