Created
June 16, 2015 21:50
-
-
Save kroehre/9cc209bcf43a1d1b001b to your computer and use it in GitHub Desktop.
match_hash
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
RSpec::Matchers.define :match_hash do |expected| | |
errors = [] | |
match do |actual| | |
errors = match_hash(expected, actual) | |
errors.empty? | |
end | |
description do |actual| | |
"matches hash #{expected}" | |
end | |
failure_message do |actual| | |
errors.join("\n") | |
end | |
def match_hash(expected, actual, errors = [], path = nil) | |
expected.each do |key, value| | |
match_value(expected[key], actual[key], errors, "#{path}#{key}/") | |
end | |
errors | |
end | |
def match_array(expected, actual, errors, path) | |
expected.each do |expected_element| | |
match_value | |
end | |
end | |
def match_value(expected, actual, errors, path) | |
if expected[key].is_a?(Hash) | |
match_hash(expected_value, actual_value, errors, path) | |
elsif expected[key].is_a?(Array) | |
match_array(expected_value, actual_value, errors, path) | |
else | |
unless expected[key] === actual[key] | |
errors << "#{path}#{key} #{actual[key]} is expected to be a case of #{expected[key]}" | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment