Situation: testing a rails application using Rspec, FactoryGirl, and VCR.
Each time a user is created, an associated Stripe user is created through the Stripe API. During testing, there really is no point in adding VCR.use_cassette or describe "...", vcr: {cassette_name: 'stripe-customer'} do ... to each specification in which user creation is involved. My actual solution is this:
RSpec.configure do |config| config.around do |example| VCR.use_cassette('stripe-customer') do |cassette| example.run end end end
But this is not sustainable, because the same cartridge will be used for every HTTP request, which, of course, is very bad.
Question: How can I use certain devices (cartridges) based on an individual request without specifying a cartridge for each specification?
I have something like this, pseudo code:
stub_request(:post, "api.stripe.com/customers").with(File.read("cassettes/stripe-customer"))
Relevant code fragments (like gist ):
# user_observer.rb class UserObserver < ActiveRecord::Observer def after_create(user) user.create_profile! begin customer = Stripe::Customer.create( email: user.email, plan: 'default' ) user.stripe_customer_id = customer.id user.save! rescue Stripe::InvalidRequestError => e raise e end end end # vcr.rb require 'vcr' VCR.configure do |config| config.default_cassette_options = { record: :once, re_record_interval: 1.day } config.cassette_library_dir = 'spec/fixtures/cassettes' config.hook_into :webmock config.configure_rspec_metadata! end # user_spec.rb describe :InstanceMethods do let(:user) { FactoryGirl.create(:user) } describe "#flexible_name" do it "returns the name when name is specified" do user.profile.first_name = "Foo" user.profile.last_name = "Bar" user.flexible_name.should eq("Foo Bar") end end end
Edit
I ended up doing something like this:
VCR.configure do |vcr| vcr.around_http_request do |request| if request.uri =~ /api.stripe.com/ uri = URI(request.uri) name = "#{[uri.host, uri.path, request.method].join('/')}" VCR.use_cassette(name, &request) elsif request.uri =~ /twitter.com/ VCR.use_cassette('twitter', &request) else end end end