Testing external API integration with VCR gem
Alexander Spitsyn
Posted on September 2, 2019
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.
💖 💪 🙅 🚩
Alexander Spitsyn
Posted on September 2, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
codenewbie My Journey Through Ruby Event Manager, Hangman, and Tackling Coolant Leaks
November 29, 2024