Posted 13 days ago. Visible to the public. Repeats.

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 end 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) { } end end


  • 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 end end end

Generated Cassette:

spec/vcr/ <model_name>/ <file_name>_<describe_title>/ <it_title>.yml
Growing Rails Applications in Practice
Check out our new e-book:
Learn to structure large Ruby on Rails codebases with the tools you already know and love.

Owner of this card:

Klaus Weidinger
Last edit:
7 days ago
by Dominik Schöler
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Klaus Weidinger to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more