Rspec how to match hash_including match hash contents

I'm trying to match Rspec arguments that contain an array of hash in a hash.

 expect(myObj).to receive(:new).with( anything, anything, anything, anything, hash_including( hash_obj: filters[:hash_obj] )

Now this hash_obj: filters[:hash_obj] has same contents, but different objects. How do I match the contents?

hash_obj is an array of hashes something like

[ { a: 1, b: 2 }, { a: 3, b: 4 }
]

1 Answer

When it comes to built-in attribute matchers (or, to be more precise, any properly designed matcher that checks for "equality" properly), you can simply nest them as deep as you need, so smth. like ... hash_including(hash_obj: include(hash_including(a: 3))) etc should work.

For example, the following expectation is green

specify do h = [ 1, "2", { 3 => [ {a: 1}, {b: 2}, {c: 3} ] } ] expect(h).to include( hash_including( 3 => include( hash_including(a: 1) ) ) )
end

So, you can follow the same approach, just adapt it to what you really would like to match.

There is one serious trade-off to be aware of, though: this approach leads to quite vague error reports when something deep is not matched. In this case, especially when you have the same expectation in several places, it might make sense to go with a custom matcher instead.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like