If the application need interaction with another web service, it’s convenience to using VCR with WebMock to test the application, rather than doing the request to another web service every time.
Setup
Modify Gemfile
group :test do gem 'webmock' gem 'vcr' end
and don’t forget to run
bundle install
Config VCR
The following code can be placed in the spec_helper.rb
VCR.configure do |c| c.allow_http_connections_when_no_cassette = true c.cassette_library_dir = 'spec/cassettes' #this specified the directory for placing the record files c.hook_into :webmock c.configure_rspec_metadata! c.default_cassette_options = { :record => :once, :erb => true, :match_requests_on => [:method, :uri, :host, :path, :headers] } end
Using VCR
Then you can using VCR when write the rspec test like:
describe 'Some api call tests', :vcr => true do #write normal api call tests here end
Re-record
Sometimes we need to re-record the cassettes, because maybe the request params changed in our app or the response is updated from third-party server.
It’s very easy to do that, just modify your VCR.config block, set record: all instead of :once.
:record => :all
and run your rspec tests related to that cassettes, then the cassettes files will be updated.
And you can specify the matchers per test:
describe 'Something', :vcr => {match_requests_on:[:method, :uri]} do # Some tests end
The following method can tell whether vcr is recording, it’s very useful in some scenarios:
VCR.current_cassette.recording?