Coding with headphones
hash_including()
So I was writing some specs today when I discovered that I needed to do something I haven’t had the need to do before: validate that a private method called by a public method received the correct parameters. Easy right? Yup should be - if its a parameratized method. In this case, its not - the method takes a hash.
So it’s not quite as simple as something like:
it "should call private_method with the correct arguments" do
some_hash = {:arg1 => "blah", :arg2 => "blah"}
@object.should_receive(:private_method).with(some_hash)
@object.public_method("something", "something_else")
end
Not as simple because, of course, we can’t guarantee the ordering of the hash and the test will sometimes (not always) fail.
Enter hash_including()
hash_including allows you to specify the same spec like this:
it "should call private_method with the correct arguments" do
some_hash = {:arg1 => "blah", :arg2 => "blah"}
@object.should_receive(:private_method).with(hash_including(some_hash))
@object.public_method("something", "something_else")
end
Looking at the source code, hash_including compares keys and values from the expected against the target and returns false if there is not match, rather than relying on ==
This also means that you don’t need to specify the complete hash, but only the important components for that spec.