DEV Community

Alexander Spitsyn
Alexander Spitsyn

Posted on Originally published at jetrockets.pro

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
end

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')
      end
    end
  end
end

See more details on the official page of the gem.

Top comments (0)