Read more

ActiveSupport includes Timecop-like helpers

Arne Hartherz
November 13, 2019Software engineer at makandra GmbH

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
    
Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

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.

Posted by Arne Hartherz to makandra dev (2019-11-13 21:38)