Posted about 1 month 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:

Copy
# 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:

Copy
# 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:

Copy
spec/vcr/ <model_name>/ <file_name>_<describe_title>/ <it_title>.yml

Once an application no longer requires constant development, it needs periodic maintenance for stable and secure operation. makandra offers monthly maintenance contracts that let you focus on your business while we make sure the lights stay on.

Owner of this card:

Avatar
Klaus Weidinger
Last edit:
about 1 month 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