I have two hashes containing arrays. In my case, the order of array elements is not important. Is there a simple way to match such hashes in RSpec2?
{ a: [1, 2] }.should == { a: [2, 1] } # how to make it pass?
P.S.
There is a matcher for arrays, that ignores the order.
[1, 2].should =~ [2, 1] # Is there a similar matcher for hashes?
SOLUTION
The solution works for me. Originally suggested by tokland, with fixes.
RSpec::Matchers.define :match_hash do |expected|
match do |actual|
matches_hash?(expected, actual)
end
end
def matches_hash?(expected, actual)
matches_array?(expected.keys, actual.keys) &&
actual.all? { |k, xs| matches_array?(expected[k], xs) }
end
def matches_array?(expected, actual)
return expected == actual unless expected.is_a?(Array) && actual.is_a?(Array)
RSpec::Matchers::BuiltIn::MatchArray.new(expected).matches? actual
end
To use the matcher:
{a: [1, 2]}.should match_hash({a: [2, 1]})
=~
does not work here, need to callRSpec::Matchers::BuiltIn::MatchArray.new(expected).matches? actual
. I have added the fix to my question above. – Aragon