diff --git a/lib/flux_capacitor.rb b/lib/flux_capacitor.rb index ba4b689..983e61f 100644 --- a/lib/flux_capacitor.rb +++ b/lib/flux_capacitor.rb @@ -26,10 +26,19 @@ def jump(seconds) end def now + return frozen_time if frozen_time Time.now_without_delorean - time_travel_offsets.inject(0){ |sum, val| sum + val } end + def freeze_time(time = Time.now, options={}) + mock_current_time time, options + @@frozen_time = Time.now + end + private + def frozen_time + @@frozen_time ||= false + end def time_travel_offsets @@time_travel_offsets ||= [] @@ -37,17 +46,23 @@ def time_travel_offsets def reset @@time_travel_offsets = [] + unfreeze_time end - def mock_current_time(time, options={}) + def mock_current_time(time, options={}) time = Chronic.parse(time, options) if time.is_a?(String) time = Time.local(time.year, time.month, time.day) if time.is_a?(Date) && !time.is_a?(DateTime) - + unfreeze_time time_travel_offsets.push Time.now - time end def restore_previous_time time_travel_offsets.pop end + + def unfreeze_time + @@frozen_time = nil + end end end + diff --git a/spec/delorean_spec.rb b/spec/delorean_spec.rb index 7830e04..573a5d2 100644 --- a/spec/delorean_spec.rb +++ b/spec/delorean_spec.rb @@ -1,7 +1,9 @@ require 'rubygems' require 'active_support/all' + require File.expand_path("../lib/delorean", File.dirname(__FILE__)) + describe Delorean do before(:all) do @@ -197,5 +199,47 @@ Time.now.should be_within(1).of(expected) end end + describe "freeze_time" do + it "should freeze the time to now" do + expected = Delorean.freeze_time + sleep 0.01 + Time.now.should be_within(0.01).of(expected) + Time.now_without_delorean.should_not be_within(0.01).of(expected) + end + + it "should freeze the time to given date" do + a_year_ago = Chronic.parse "1 year ago" + Delorean.freeze_time a_year_ago + sleep 0.01 + expected = a_year_ago + Time.now.should be_within(0.01).of(expected) + Time.now_without_delorean.should_not be_within(0.01).of(expected) + end + + it "should unfreeze on new time travel" do + a_year_ago = Chronic.parse "1 year ago" + Delorean.freeze_time a_year_ago + Delorean.jump 12 + expected = Time.now + sleep 0.01 + Time.now.should be_within(13).of(a_year_ago) + Time.now.should_not be_within(0.01).of(expected) + Delorean.freeze_time + Delorean.time_travel_to a_year_ago + expected = Time.now + sleep 0.01 + Time.now.should_not be_within(0.01).of(expected) + end + + it "should back_to_the_present after freezen" do + expected = Time.now + a_year_ago = Chronic.parse "1 year ago" + Delorean.freeze_time a_year_ago + Delorean.back_to_the_present + Time.now.should be_within(1).of(expected) + end + + end end +