Thursday, November 4, 2010

Time Equivalence or Closeness in RSpec

If you have two times in RSpec that you want to make sure are equal, you could use:
kid.sleepy_at.should eq(bedtime)
But, that only checks to make sure that the time to the nearest second is equal.

To be more exact than a rounded second use:

kid.sleepy_at.to_f.should eq(bedtime.to_f)

If you want to ensure that a time is just close to the expected time, use be_close.

For example, if sleepy_at should be within a half second of bedtime use:

kid.sleepy_at.to_f.should be_close(bedtime.to_f, 0.5)
Converting time to float with to_f doesn't look pretty when it fails, but if you don't use it, and use:
kid.sleepy_at.should be_close(bedtime, 0.5)
then it is comparing seconds, and you might get an error like:
Failure/Error: kid.sleepy_at.should be_close(bedtime, 0.5)
expected Thu Nov 04 20:50:21 UTC 2010 +/- (< 0.5), got 2010-11-04 20:50:22 UTC
This is due to the second being rounded off.

To make sure they are within a rounded second of each other, use:

kid.sleepy_at.should be_close(bedtime, 1)

No comments: