I have two hashes h1
and h2
that I'd like to compare in RSpec.
I want to check that the elements of h1
are the same as h2
after some transformation, which we'll call f
. That is, I want to verify that for every key k
in h1
, h1[k] == f(h2[k])
.
For example, if all the values in h2
are twice as big as the corresponding values in h1
, then I want to check that for every key k
in h1, h2[k] == h1[k] * 2
.
What's the right way to do this in RSpec? Currently I do:
h1 = ...
expect(
h2.all? { |k,v|
v == f(h1[k])
}
).to be true
but that seems clunky.
Best Answer
Sounds like what you are testing is the transformation. I would consider writing something like this:
To me the description clearly states what we are expecting. Then I can easily see from the test what the input is and the expected output. Also, this leverages the hash matcher which will provide a nice diff of the two hashes on a failure:
Though I would question what the key-value relationship means. Are these simply test cases you are trying to run through? If so, I'd just make each a unique tests. If there is something more to it, then I may question why the transform method isn't provided the hash to start with.