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

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

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.