-
-
Save TylerRick/fd77ff6b7f8ce53148cdd67dae26e6a5 to your computer and use it in GitHub Desktop.
Custom RSPec matcher for detailed hash compasion and diff
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
require 'facets/hash/recurse' | |
# Usage: | |
# expect(actual).to match_hash(expected) | |
# | |
RSpec::Matchers.define :match_hash do |expected| | |
match do |actual| | |
# Sort hashes before comparing so that the diff only shows actual changes between keys and | |
# values. | |
actual = actual.recurse {|h| h.sort_by {|k,v| k.to_s }.to_h } | |
expected = expected.recurse {|h| h.sort_by {|k,v| k.to_s }.to_h } | |
is_match = actual == expected | |
unless is_match | |
system( | |
# If [diff-so-fancy](https://github.com/so-fancy/diff-so-fancy) is available, use it | |
if (system('which diff-so-fancy >/dev/null'); $?.success?) | |
"git diff $(echo '#{JSON.pretty_generate(expected)}' | git hash-object -w --stdin) " + | |
"$(echo '#{JSON.pretty_generate(actual )}' | git hash-object -w --stdin) | diff-so-fancy cat -" | |
else | |
"git diff $(echo '#{JSON.pretty_generate(expected)}' | git hash-object -w --stdin) " + | |
"$(echo '#{JSON.pretty_generate(actual )}' | git hash-object -w --stdin) --word-diff | cat -" | |
end, | |
out: $stdout, | |
err: :out | |
) | |
end | |
is_match | |
end | |
failure_message { 'Look at the Diff above! ^^^' } | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks for explaining, very useful gist 👍