Read more

RSpec: automatic creation of VCR cassettes

Klaus Weidinger
October 11, 2021Software engineer at makandra GmbH

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

Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

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

Behaviour

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

# 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
Posted by Klaus Weidinger to makandra dev (2021-10-11 13:50)