Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Tom Ward

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Using time travel to unit test time-based data

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.

   1  
   2  class << Time
   3    unless method_defined? :now_before_time_travel
   4      alias_method :now_before_time_travel, :now
   5    end
   6    
   7    def now 
   8      @now || now_before_time_travel 
   9    end 
  10    
  11    def travel_to(time, &block)
  12      @now = time
  13      block.call
  14    ensure
  15      @now = nil
  16    end
  17  end


   1  
   2  def test_something_involving_time
   3    account = Time.travel_to(creation_time = Time.now) do
   4      Account.new  
   5    end
   6  
   7    assert_equal creation_time, account.creation_time
   8  end
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS