Common Custom Matchers

alainravet edited this page Aug 22, 2012 · 5 revisions

This is a list of common matcher patterns that you might want to use. Note that custom request matchers are only supported on VCR 2.0.0.beta1 and above. See this blog post for information about them.

Please feel free to add your own, if you feel others could use it.

Body with ignored order

This matcher allows you to match against the body of your requests, but ignore the order in which the body-elements are sent.

This is useful if you use a HTTP library that accepts a Hash of body-elements, which would result in the body-part of the request becoming unpredictable and therefore might cause VCR to recognize it as a new request.

VCR.configure do |c|
  c.register_request_matcher :body do |request1, request2|
    body1 = request1.body.split('&')
    body2 = request2.body.split('&')
    (body1 - body2).empty?
  end
end

URI ignoring query parameter ordering

Sometimes the order of your URI query does not matter. If for some reason your specs keep failing and everything is the same except the order of the query params then use this.

require 'cgi'

VCR.configure do |c|
  c.register_request_matcher :ignore_query_param_ordering do |r1, r2|
    uri1 = URI(r1.uri)
    uri2 = URI(r2.uri)

    uri1.scheme == uri2.scheme &&
      uri1.host == uri2.host &&
        uri1.path == uri2.path &&
          CGI.parse(uri1.query||'') == CGI.parse(uri2.query||'')
  end
end