RSpec: automatic creation of VCR cassettes

This RailsCast Archive demonstrated a very convenient method to activate VCR for a spec by simply tagging it with :vcr.

For RSpec3 the code looks almost the same with a few minor changes. If you have the vcr and webmock gems installed, simply include:

# spec/support/vcr.rb
VCR.configure do |c|
  c.cassette_library_dir = Rails.root.join("spec", "vcr")
  c.hook_into :webmock

RSpec.configure do |c|
  c.around(:each, :vcr) do |example|
    name = example.metadata[:full_description].split(/\s+/, 2).join("/").underscore.gsub(/[^\w\/]+/, "_")
    options = example.metadata.slice(:record, :match_requests_on).except(:example_group)
    VCR.use_cassette(name, options) { }


  • If a spec is not tagged with :vcr, VCR will complain about any attempted HTTP request. This is the default behaviour. If you want to turn this off temporarily, e.g. to communicate with an actual API while writing a new spec, simply add the line c.allow_http_connections_when_no_cassette = true to the VCR.configure-block.

  • If a spec is tagged with :vcr, a cassette with an automatically determined name will be generated on the first test run and replayed on subsequent runs:


# spec/models/<model_name>/<file_name>_spec.rb
describe ModelName::ExampleApi do

  describe '<describe_title>' do
    it '<it_title>', :vcr do
      # calls to API
      # expectations

Generated Cassette:

Klaus Weidinger 8 months ago
This website uses short-lived cookies to improve usability.
Accept or learn more