notahat / time_travel

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

This URL has Read+Write access

name age message
file .gitignore Sun Aug 24 07:59:53 -0700 2008 Wrote a test for Marcus's patch to pass the tim... [notahat]
file MIT-LICENSE Sat Mar 08 20:16:18 -0800 2008 Initial import. git-svn-id: http://svn.notaha... [pete]
file README.rdoc Loading commit data...
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