Testing external API integration with VCR gem

Suppose your application connects to an external service via API and you have a wrapper for this API that handles and parses response. The VCR gem gives you ability to store parsed response in a special format (cassetes). VCR makes a real request to the API for the first test run and writes it's response to the cassete for next test runnings.

First you need to set VCR configuration:

VCR.configure do |config|

  config.cassette_library_dir = "spec/vcr_cassettes"

  config.hook_into :webmock


And then write specs like the following:

RSpec.describe ExternalService do

  describe '#new_order' do

    let(:params) { { foo: 'bar' } }

    it 'creates new order' do

      VCR.use_cassette("external_service") do

        result = subject.new_order(params) # makes HTTP POST to an external service

        expect(result.successful?).to be_truthy

        expect(result.data).to have_key('order_id')





See more details on the official page of the gem.

3f70c59a 83c4 49ba 8ef5 1ae2b375a2b4 rectangle 400 x

Full-Stack Developer at JetRockets