ruby - Using specific VCR cassette based on request -


situation: testing rails application using rspec, factorygirl , vcr.

every time user created, associated stripe customer created through stripe's api. while testing, doesn't makes sense add vcr.use_cassette or describe "...", vcr: {cassette_name: 'stripe-customer'} ... every spec user creation involved. actual solution following:

rspec.configure |config|   config.around |example|     vcr.use_cassette('stripe-customer') |cassette|       example.run     end   end end 

but isn't sustainable because same cassette used every http request, of course bad.

question: how can use specific fixtures (cassettes) based on individual request, without specifying cassette every spec?

i have in mind, pseudo-code:

stub_request(:post, "api.stripe.com/customers").with(file.read("cassettes/stripe-customer")) 

relevant pieces of code (as 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 |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   let(:user) { factorygirl.create(:user) }    describe "#flexible_name"     "returns name when name specified"       user.profile.first_name = "foo"       user.profile.last_name = "bar"        user.flexible_name.should eq("foo bar")     end   end end 

edit

i ended doing this:

vcr.configure |vcr|   vcr.around_http_request |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 

vcr 2.x includes feature support use cases these:

https://relishapp.com/vcr/vcr/v/2-4-0/docs/hooks/before-http-request-hook! https://relishapp.com/vcr/vcr/v/2-4-0/docs/hooks/after-http-request-hook! https://relishapp.com/vcr/vcr/v/2-4-0/docs/hooks/around-http-request-hook!

vcr.configure |vcr|   vcr.around_http_request(lambda { |req| req.uri =~ /api.stripe.com/ }) |request|     vcr.use_cassette(request.uri, &request)   end end 

Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -