Using VCR in tests

VCR is a gem that is super helpful if your Ruby application is using an external API. When testing, if an actual API is called, this will result in slow test performance. Although a single test may not seem that slow when run individually, the impact of using many API calls in tests will significantly slow down the time it takes to run tests.

    This is why VCR is so handy! What it allows you to do is to record a ‘cassette’ of your API request and will save the results and then use the cassette in testing from then on. This means that once set up, the first time that the test is run, VCR uses the actual API and records the actual response in a (pretend!) ‘cassette’, this saved response is then used in place of using the actual API each time the test is run. The benefits of this is that now your tests will run faster, but also that the tests will not be dependent on the external service working.

How to install and use VCR:

  1. Add VCR gem to your gemfile:
gem 'vcr'

And run:

➜ ~ bundle install
  1. Create spec/support/vcr_setup.rb and use the following code:
VCR.configure do |c|
 # The directory where your cassettes will be saved
 c.cassette_library_dir = 'spec/vcr'
 # Your HTTP request service. You can use whichever is your preference.
 c.hook_into :webhook
  1. Now that setup is complete, it’s time to put VCR into action and test out the API call in question:
# spec/api/widgets_spec.rb
RSpec.describe 'API::Widgets', vcr: true do
 # Any tests making external requests in here will now use vcr

The first time this test is run, VCR will create a new cassette and store it in the corresponding location, so in this instance spec/vcr/api/widgets_spec.yaml.

And that’s it! That is the basic setup and usage of VCR. There are plenty of configuration options available, such as setting a timeframe in which it should automatically re-write the cassette (and making a new API call). Do check the documentation.

By Poppy Rodgers

Developer at Resolver