class WebMock::BodyPattern
Constants
- BODY_FORMATS
Public Class Methods
new(pattern)
click to toggle source
# File lib/webmock/request_pattern.rb, line 169 def initialize(pattern) @pattern = if pattern.is_a?(Hash) normalize_hash(pattern) elsif rSpecHashIncludingMatcher?(pattern) WebMock::Matchers::HashIncludingMatcher.from_rspec_matcher(pattern) else pattern end end
Public Instance Methods
matches?(body, content_type = "")
click to toggle source
# File lib/webmock/request_pattern.rb, line 179 def matches?(body, content_type = "") if (@pattern).is_a?(Hash) return true if @pattern.empty? matching_hashes?(body_as_hash(body, content_type), @pattern) elsif (@pattern).is_a?(WebMock::Matchers::HashIncludingMatcher) @pattern == body_as_hash(body, content_type) else empty_string?(@pattern) && empty_string?(body) || @pattern == body || @pattern === body end end
to_s()
click to toggle source
# File lib/webmock/request_pattern.rb, line 192 def to_s @pattern.inspect end
Private Instance Methods
body_as_hash(body, content_type)
click to toggle source
# File lib/webmock/request_pattern.rb, line 197 def body_as_hash(body, content_type) case BODY_FORMATS[content_type] when :json then WebMock::Util::JSON.parse(body) when :xml then Crack::XML.parse(body) else WebMock::Util::QueryMapper.query_to_values(body) end end
empty_string?(string)
click to toggle source
# File lib/webmock/request_pattern.rb, line 246 def empty_string?(string) string.nil? || string == "" end
matching_hashes?(query_parameters, pattern)
click to toggle source
Compare two hashes for equality
For two hashes to match they must have the same length and all values must match when compared using `#===`.
The following hashes are examples of matches:
{a: /\d+/} and {a: '123'} {a: '123'} and {a: '123'} {a: {b: /\d+/}} and {a: {b: '123'}} {a: {b: 'wow'}} and {a: {b: 'wow'}}
@param [Hash] query_parameters typically the result of parsing
JSON, XML or URL encoded parameters.
@param [Hash] pattern which contains keys with a string, hash or
regular expression value to use for comparison.
@return [Boolean] true if the paramaters match the comparison
hash, false if not.
# File lib/webmock/request_pattern.rb, line 231 def matching_hashes?(query_parameters, pattern) return false unless query_parameters.is_a?(Hash) return false unless query_parameters.keys.sort == pattern.keys.sort query_parameters.each do |key, actual| expected = pattern[key] if actual.is_a?(Hash) && expected.is_a?(Hash) return false unless matching_hashes?(actual, expected) else return false unless expected === actual end end true end
normalize_hash(hash)
click to toggle source
# File lib/webmock/request_pattern.rb, line 250 def normalize_hash(hash) Hash[WebMock::Util::HashKeysStringifier.stringify_keys!(hash).sort] end