Today I Learned

A Hashrocket project

Time travelling in rspec/rails

When basing logic on the current time its helpful for testing to have a stable time. A time that does not change. Rails has a module ActiveSupport::Testing::TimeHelpers that was added in Rails 4.2 to provide methods that manipulate the time during testing.

travel_to(Time.parse("2017-01-19")) do
  puts Time.now.strftime(:date)
end

puts Time.now.strftime(:date)

The above code outputs 2017-01-19 and 2017-05-02 (the current date). A fun way to time travel in modern ruby.

Looking for help? Hashrocket provides expert Ruby on Rails development. We’ve built hundreds of high–quality Ruby on Rails applications over the past decade. Contact us today and find out how we can help you.