When writing tests, it's sometimes difficult to test results of methods that use current time. Two calls to Time.now can give different results and cause test failures. Here is some code that lets you execute a block during which Time.now will return a consistent value:
class Time
class << self
def now
@time || orig_new
end
alias_method :orig_freeze, :freeze
alias_method :orig_new, :new
alias_method :new, :now
def freeze(time = nil)
raise "A block is required" unless block_given?
begin
prev = @time
@time = time || now
yield
ensure
@time = prev
end
end
def frozen?
!@time.nil?
end
end
end