public
Description: A Rails plugin that makes it easy to write tests or specs for time-dependent code
Homepage: http://notahat.com/time_travel
Clone URL: git://github.com/notahat/time_travel.git
notahat (author)
Wed Sep 03 08:54:58 -0700 2008
commit  cfc0c817dc7ff3bf5f11a30f3e32c3ba36532fd7
tree    25e57ddc8e83a144d3f98674cabc4d98ed24946b
parent  8ddfb85b1977dbdf236a6d0921a82d827a59b327
name age message
file .gitignore Loading commit data...
file MIT-LICENSE
file README.rdoc
file Rakefile
file init.rb Sat Mar 08 20:16:18 -0800 2008 Initial import. git-svn-id: http://svn.notaha... [pete]
directory lib/
directory spec/
README.rdoc

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, or a String to parse 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.

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