Timecop Gotcha

Timecop is an extremely useful gem which allows you to simulate the passing of time in RSpec tests. We’re using it to test parts of Citrulu – for example, making sure we don’t send you multiple emails about the same thing.

One of our tests has this shape:

it "should do some stuff!" do
  # do something
  Timecop.travel(Time.now + 5)
  # do something 5 seconds later
  Timecop.travel(Time.now + 10)
  # do something 10 seconds later

  result.should be_awesome
end

When running the test I noticed the following line in the output:

15.74 seconds ./spec/lib/my_awesome_spec.rb:118

Over 15 seconds to run the spec?
Clearly the elapsed time is calculated based on timestamps which are affected by the TimeCop travel statements. Adding Timecop.return() at the end of the script fixes this by resetting the test time to the system time:

0.71269 seconds ./spec/lib/my_awesome_spec.rb:118

Much more plausible 🙂