So I needed to test “time”…quite literally. I needed to test some time-related validity logic in Rails.
I read that in Rails 4.1, ActiveSupport::Testing::TimeHelpers was added to make it easier for everyone to withstand the test of time. Err, I mean to test time. No disrespect to TimeCop, I know it has its own advantages, but the built-in time helpers for Rails was just enough for my needs.
travel method accepts the time/date difference from Time.now. For example, you want to go to next week, you can
travel(1.week) and boom! You’re there.
travel_to accepts stubbed Time or Date. For example,
travel_to Time.new(2004, 9, 20) and voila! You’re back to my 16th birthday.
travel_to are used without a block,
travel_back is needed to go back to the “real” time. Otherwise, it will go back to its original state on its own at the end of the block.
So there. That’s basically how to time travel using ActiveSupport TimeHelpers.