Well the problem is that they will all fail eventually. This is the
deal, we have date X, let's say that it's yesterday. My program uses
some SQL statements to check if date X (which is obviously in a
database) was within Y amount of days. But date X will no longer be in
that range after so many days, so I either have to make it dynamically
generated (no fun and possible error prone) or somehow make the computer
think that the current date and time is a certain value.
I've been using the foloowing code for a while to do exactly that:
## BEGIN time_warp.rb ##
class Time #:nodoc:
class <<self
attr_accessor :warp
alias_method :real_now, :now
def now
warp
end
alias_method :new, :now
end
end
Time.warp = Time.real_now
def pretend_now_is(time)
begin
Time.warp = time
yield
ensure
Time.warp = Time.real_now
end
end
## END time_warp.rb ##
I'm not the original author. I grabbed the code of one of the numerous
code pasting sites quite a while ago, and I no longer remember exactly
where it came from.
At any rate, you can use that in your tests like so:
## Begin test_relative_time.rb ##
require 'time_warp'
require 'test/unit'
class TestRelativeTime < Test::Unit::TestCase
DAY = 86400
def test_should_not_really_be_within_1_day_of_2005_07_04
assert( ( Time.now - Time.mktime( 2005, 7, 4 ) ).abs > DAY )
end
def test_should_pretend_to_be_within_1_day_of_2005_07_04
pretend_now_is( Time.mktime( 2005, 7, 5 ) ) do
assert( ( Time.now - Time.mktime( 2005, 7, 4 ) ).abs <= DAY )
end
end
end
## END test_relative_time.rb ##
Hope that helps.