Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Using Time Travel To Unit Test Time-based Data

DZone's Guide to

Using Time Travel To Unit Test Time-based Data

·
Free Resource
Searching for a way to test time-based data in ruby, I came across an excellent suggestion from Rick Olson (technoweenie).  I've cleaned it a little to make it clearer to read, but the main credit should go to Rick.


class << Time
  unless method_defined? :now_before_time_travel
    alias_method :now_before_time_travel, :now
  end
  
  def now 
    @now || now_before_time_travel 
  end 
  
  def travel_to(time, █)
    @now = time
    block.call
  ensure
    @now = nil
  end
end



def test_something_involving_time
  account = Time.travel_to(creation_time = Time.now) do
    Account.new  
  end

  assert_equal creation_time, account.creation_time
end
Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}