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 book lover

Growing Rails Applications in Practice

Check out our e-book. Learn to structure large Ruby on Rails codebases with the tools you already know and love.

  • Introduce design conventions for controllers and user-facing models
  • Create a system for growth
  • Build applications to last
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)