Skip to content

Instantly share code, notes, and snippets.

@kroehre
Created June 16, 2015 21:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kroehre/9cc209bcf43a1d1b001b to your computer and use it in GitHub Desktop.
Save kroehre/9cc209bcf43a1d1b001b to your computer and use it in GitHub Desktop.
match_hash
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