ActiveSupport includes Timecop-like helpers

Updated . Posted . Visible to the public. Repeats.

ActiveSupport (since 4.1) includes test helpers to manipulate time, just like the Timecop gem Show archive.org snapshot :

  • To travel a relative amount of time, use travel:

    travel 1.day
    
  • To travel to a specific moment in time, use travel_to:

    travel_to 1.hour.from_now
    
  • To freeze the current time, use freeze_time (ActiveSupport 5.2+):

    freeze_time
    

All those methods may also receive a block to call and restore time afterwards. If you don't provide a block, you must call travel_back or unfreeze_time (ActiveSupport 6+, alias for travel_back) once you are done.

Note

When freezing time with #travel_to, time will be frozen (like with freeze_time). This means that your application can't detect passage of time by using Time.now.

Simply load the TimeHelpers module as required by your test framework. Example:

RSpec.configure do |config|
  config.include ActiveSupport::Testing::TimeHelpers
end

Timecop behaves differently and allows for more flexibility. We use it in many projects, and it's a good fit. If you don't need its features, ActiveSupport's time helpers might be good enough.

Arne Hartherz
Last edit
Michael Leimstädtner
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2019-11-13 20:38)