Using VCR with WebMock in Rails Rspec Tests

By | 2014 年 1 月 11 日

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.


Modify Gemfile

group :test do
  gem 'webmock'
  gem 'vcr'

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.default_cassette_options = {
    :record => :once,
    :erb => true,
    :match_requests_on => [:method, :uri, :host, :path, :headers]

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


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

The following method can tell whether vcr is recording, it’s very useful in some scenarios:



电子邮件地址不会被公开。 必填项已用*标注