Skip to content

A Rails plugin that makes it easy to write tests or specs for time-dependent code

License

Notifications You must be signed in to change notification settings

notahat/time_travel

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

17 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

TimeTravel

Time Travel is a Rails plugin that makes it easy to write tests or specs for time-dependent code. It provides the at_time function:

at_time("9 March 2018 2:32") do
  ...
end

Inside the block, Time.now will return the given time. The time will be restored to normal system time when the block exits.

The at_time function can take a Time object, a Date, or a String to parse them into a time.

If the time is given as a String, it is parsed using Time.zone.parse (in Rails 2.1) or Time.parse (in Rails 2.0 and earlier). That means it will be interpreted as being in the current timezone, unless you provide an explicit timezone in the string.

If the time is given as a Date, it is converted to a String and then parsed in the described way.

You can also access the current time inside of the block via a block parameter, eg:

at_time Time.now do |time|
  ...
end

closest_second

The closest_second method is useful when you need to compare an ActiveRecord datetime value with a Ruby Time.

Times are normally stored in your database with 1 second resolution, but Ruby’s Time class has microsecond resolution. That means that this will usually fail:

at_time(Time.now) do  # Freeze the time to a single value for the block.
  @post = Post.create(:title => 'Example')
  @post.reload
  @post.created_at.should == Time.now  # Time.now has some number of microseconds, but @post.created_at doesn't.
end

The closest_second method returns the time without the microseconds, so the following will succeed:

@post.created_at.should == Time.now.closest_second

Installation

ruby script/plugin install git://github.com/notahat/time_travel.git

About

A Rails plugin that makes it easy to write tests or specs for time-dependent code

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages