rspecrspec-railsspecificationsvcr

When using vcr / cassettes in rspec, is there a way to change match_requests_on per test?


I'm using vcr in rspec to match save urls and play them back, in the config I'm using the following settings for match_requests_on :

match_requests_on: [:method, :host, :path]

However I want to modify this config for certain urls only, for example if a url contains /somepath/ then I want to change the config for this url only to match_requests_on: [:method, :host, :path, :body] is there a way to do this in the vcr or rspec config files?

I can't seem to find anywhere that will change it per vcr call globally.


Solution

  • You'd need to probably go with a custom matcher.

    A matcher is just a Proc/lambda called with two params: request_1 and request_2. Responding true when equal, false otherwise.

    There's a whole feature describing how to do it: https://relishapp.com/vcr/vcr/v/5-1-0/docs/request-matching/register-and-use-a-custom-matcher#use-a-callable-as-a-custom-request-matcher

    so what you'd want is

    my_fancy_matcher = lambda do |r1, r2|
    case r1.path # IDK if path is a real method, but it's just an example
      when '/foo' 
        r1.parsed_uri == r2.parsed_uri
      when '/bar'
        r1.method == r2.method && r1.parsed_uri == r2.parsed_uri
      else
        false
    end
    

    and use it directly

    VCR.use_cassette('hatever', match_requests_on: [my_fancy_matcher]) do 
      ## tests here
    end
    

    When you get the lambda working as you'd like, and if you're using it everywhere in your specs, you can register it:

    VCR.configure do |c|
      c.hook_into :webmock
      c.cassette_library_dir = 'cassettes'
      c.register_request_matcher :my_fancy_matcher do |request_1, request_2|
        # the logic here
      end
    end