How To Use The VCR Gem With Rails And Rspec

So yesterday I spent way too much time trying to make this really cool VCR gem work with my rspec tests. The problem was that most of the tutorials out there were pretty outdated, and things have changed a bit.

The VCR gem is really useful if you have methods that need to make an api request. You don’t want to make api requests during tests, especially if the api has some kind of rate limit (I’m looking at you Twitter!).

So what you could do is create a text file mocking the response you get from the web service you’re making the api to and do the tests that way, or you can use the VCR gem! The VCR gem makes an api request once, and records the response to a cassette, which it then uses in future tests. Clever, no?

Here’s how you set up the VCR gem in your Rails App with Rspec:

Get The Gems

In your Gemfile, make sure to add the vcr gem along with a gem that does the HTTP interaction. The VCR gem supports the following HTTP request services, which also have nice gems:

  • FakeWeb
  • WebMock
  • Typhoeus

For a complete list of these, check out the VCR gem page on Github. I will be using Typhoeus in my example, so my Gemfile includes the vcr and the typhoeus gems:

# Gemfile
gem 'typhoeus', '0.4.2'

group :development, :test do
  gem 'vcr', '2.2.5'

Don't forget to run 'bundle install' after you add these gems!

Set Up Support

Create a spec/support directory, and add a vcr_setup.rb file to it. In the vcr_setup.rb file, add your VCR configuration.

# spec/support/vcr_setup.rb
VCR.configure do |c|
  #the directory where your cassettes will be saved
  c.cassette_library_dir = 'spec/vcr'
  # your HTTP request service. You can also use fakeweb, webmock, and more
  c.hook_into :typhoeus

Note that I also added a spec/vcrdirectory. This is where my cassettes will be saved.

Take a look at the documentation for additional configuration options.

Add some test!

Now you are ready to add your Rspec tests. Simply put the web request part of your tests in a VCR.use_cassette block.

# spec/model/your_model_spec.rb
describe YourModel do
  describe '#call_api" do
     it "gets a response from an api" do
       VCR.use_cassette 'model/api_response' do
          response = call_api(api_url)
          response.first.should == "hello world"

When you run this test for the first time, check your spec/vcr directory. You will see a new directory called ‘model’, and in it will be the api_response.yml file, which will include the response from the api that you just called. Now, every time the test runs, that cassette will be used instead of making the actual api call.

Enjoy the article? Join over 20,000+ Swift developers and enthusiasts who get my weekly updates.