This will be a quick post that documents an interesting find in RSpec.
I encountered a classic Ruby testing failure. I have an object whose method takes 2 time values, a start datetime and an end datetime. The intent of the method is to find records matching those values and send an e-mail to a related User account.
As many experienced Ruby programmers have seen, the failure looks like this:
Upon closer inspection, you will notice that the values appear to be exactly the same. You may ask yourself then, “Why is there a failure if the values are the same?”.
One of the possible reasons why this spec failed is that while the datetime values match down to the second, they’re probably mismatching on the millisecond. The accepted solution is to use the be_within matcher.
If you’re comparing time or date/time values, you can stop there. However, my use case has a twist on it. Instead of comparing whether or not the time value is what I expect, I wanted to ensure that the method I’m calling is passed the appropriate time values.
As you can see, I don’t care if the values are equal down to the millisecond, all I care is that it’s the appropriate value passed in. RSpec makes no such distinction, nor should it.
Having consulted a few peeps on Twitter, including Myron Marston, I got my answer. The be_within matcher can be used within a with call!
According to the RSpec documentation, a_value_within is an alias of be_within.
I think this is a pretty cool and pretty powerful part of RSpec and I confess that I was not aware of it AT ALL.
Hopefully, this will save someone time in the future.