Skip to content

Instantly share code, notes, and snippets.

@ardecvz
Last active May 14, 2024 08:22
Show Gist options
  • Save ardecvz/2bca1678badad973ce2236c66fddac76 to your computer and use it in GitHub Desktop.
Save ardecvz/2bca1678badad973ce2236c66fddac76 to your computer and use it in GitHub Desktop.
A VCR trick to include preparation and cleanup phases for external services directly within the test files (the phases run ONLY when recording cassettes)
# frozen_string_literal: true
# A VCR trick to include preparation and cleanup phases for external services
# directly within the test files (the phases run ONLY when recording cassettes):
#
# RSpec.describe EvilMartiansAPI::Client, vcr: true do
# let(:client) { described_class.new }
#
# let(:developer_team_number) { 42 }
#
# vcr_recording_setup { client.create_developer(developer_team_number) }
# vcr_recording_teardown { client.delete_developer(developer_team_number) }
#
# it 'starts the project with a freshly created developer in the team' do
# client.start_the_next_big_thing([developer_team_number])
# end
# end
#
# For more details, see https://evilmartians.com/chronicles/ideal-http-client#testing
#
module VCRIntro
module DSL
def vcr_recording_setup(*args, &block)
before(*args) { VCRIntro.run_without_cassette_recording(&block) }
end
def vcr_recording_teardown(*args, &block)
after(*args) { VCRIntro.run_without_cassette_recording(&block) }
end
end
module_function
def setup
VCR.configuration.ignore_request { Thread.current[:vcr_skip_cassette_recording] }
end
def run_without_cassette_recording(&block)
return unless cassette_recording?
Thread.current[:vcr_skip_cassette_recording] = true
block.call
ensure
Thread.current[:vcr_skip_cassette_recording] = false
end
def cassette_recording?
VCR.current_cassette&.recording?
end
end
RSpec.configure do |config|
config.before(:suite) { VCRIntro.setup }
end
RSpec::Core::ExampleGroup.extend VCRIntro::DSL
@Samsinite
Copy link

Getting:

XXX is not available on an example group (e.g. a `describe` or `context` block). It is only available from within individual examples (e.g. `it` blocks) or from constructs that run in the scope of an example (e.g. `before`, `let`, etc).

Which doesn't make sense to me because it is running in a before construct, any ideas?

@Samsinite
Copy link

Samsinite commented Oct 11, 2023

@ardecvz Follow up, for some reason, the only thing I could get to work was this:

before do
  VcrHelpers.run_without_cassette_recording do
    # setup data for test
  end
end

after do
  VcrHelpers.run_without_cassette_recording do
    # destroy data used in test
  end
end

If you have any ideas why vcr_recording_setup wasn't working, it'd be much appreciated. Using rails 6.1.7, rspec 3.10.0, and rspec-rails 5.0.1. Regardless, the strategy was helpful for me, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment