Permalink
Browse files

allowing regex to be used in hash pattern matching

  • Loading branch information...
1 parent 337740f commit ce5db2bc4d5c0fc37887146a7a2b6b7fb5022879 @GBH GBH committed Mar 27, 2011
Showing with 21 additions and 4 deletions.
  1. +15 −3 lib/webmock/request_pattern.rb
  2. +6 −1 spec/request_pattern_spec.rb
@@ -143,11 +143,11 @@ def matches?(body, content_type = "")
case BODY_FORMATS[content_type]
when :json then
- Crack::JSON.parse(body) == @pattern
+ matching_hashes?(Crack::JSON.parse(body), @pattern)
when :xml then
- Crack::XML.parse(body) == @pattern
+ matching_hashes?(Crack::XML.parse(body), @pattern)
else
- Addressable::URI.parse('?' + body).query_values == @pattern
+ matching_hashes?(Addressable::URI.parse('?' + body).query_values, @pattern)
end
else
empty_string?(@pattern) && empty_string?(body) ||
@@ -161,6 +161,18 @@ def to_s
end
private
+
+ def matching_hashes?(h1, h2)
+ return false if h1.size != h2.size
+ h1.each do |k, v|
+ if v.is_a?(Hash) && h2[k].is_a?(Hash)
+ return false unless matching_hashes?(v, h2[k])
+ else
+ return false unless h2[k] === v
+ end
+ end
+ true
+ end
def empty_string?(string)
string.nil? || string == ""
@@ -145,7 +145,7 @@ def match(request_signature)
WebMock::RequestPattern.new(:get, "www.example.com", :query => {"a" => ["b", "c"]}).
should_not match(WebMock::RequestSignature.new(:get, "www.example.com?x[]=b&a[]=c"))
end
-
+
it "should match for query params are the same as declared as string" do
WebMock::RequestPattern.new(:get, "www.example.com", :query => "a[]=b&a[]=c").
should match(WebMock::RequestSignature.new(:get, "www.example.com?a[]=b&a[]=c"))
@@ -223,6 +223,11 @@ def match(request_signature)
WebMock::RequestPattern.new(:post, 'www.example.com', :body => body_hash).
should_not match(WebMock::RequestSignature.new(:post, "www.example.com", :body => 'foo bar'))
end
+
+ it "should match when hash contains regex values" do
+ WebMock::RequestPattern.new(:post, "www.example.com", :body => {:a => /^\w{5}$/, :b => {:c => /^\d{3}$/}}).
+ should match(WebMock::RequestSignature.new(:post, "www.example.com", :body => 'a=abcde&b[c]=123'))
+ end
end

0 comments on commit ce5db2b

Please sign in to comment.