[LRUG] Stubbing Time.zone.now

Will Tomlins will.tomlins at unboxedconsulting.com
Mon Aug 2 02:50:08 PDT 2010


Hi People,

I'm having a strange issue with stubbing time and I was wondering if 
anyone here could shed a little light on the issue.

Firstly I am trying to stub Time.zone.now in Cucumber  # Waits while the 
calls of "/don't stub time in cucumber/" die down #.  So the feature I'm 
writing explicitly required different behaviour based on the current 
time, and I would like the language of the feature to reflect this.

What I have at the moment:

When /^I time-travel to "([^\"]*)"$/ do |time_string|
   time = Time.zone.parse(time_string)
   Time.zone.stub!(:now).and_return(time)
end

Then "I return to the present day" do
   Time.zone.unstub!(:now)
end

And my features go along these lines:

     When I time-travel to "2010/01/01 10:00:00"
     And I go to the home page
     Then I should see XXXXXXXXXXXXXXXXXXX
     Then I return to the present day


And I've got 2 scenarios running which use these quantum leaps.  Each 
scenario runs and passes when run on their own, but the second will fail 
if the two are run together.  After a bit more digging I found that 
Time.zone.now cannot be stubbed if it has previously been unstubbed.

Thus:

(rdb:1) Time.zone.stub!(:now).and_return(:something)
#<Proc:0x051b55a8@/Users/will/Sites/five-tv/vendor/gems/rspec-1.3.0/lib/spec/mocks/message_expectation.rb:61>
(rdb:1) Time.zone.now
:something

(rdb:1) Time.zone.stub!(:now).and_return(:something_else)
#<Proc:0x051b55a8@/Users/will/Sites/five-tv/vendor/gems/rspec-1.3.0/lib/spec/mocks/message_expectation.rb:61>
(rdb:1) Time.zone.now
:something_else

(rdb:1) Time.zone.unstub!(:now)
#<Spec::Mocks::MessageExpectation:0x512c5dc @at_most=nil, 
@exception_to_raise=nil, @args_to_yield_were_cloned=false.......
(rdb:1) Time.zone.now
Mon, 02 Aug 2010 10:28:56 BST +01:00

(rdb:1) Time.zone.stub!(:now).and_return(:another_thing)
#<Proc:0x051b55a8@/Users/will/Sites/five-tv/vendor/gems/rspec-1.3.0/lib/spec/mocks/message_expectation.rb:61>
(rdb:1) Time.zone.now
Mon, 02 Aug 2010 10:29:12 BST +01:00

I have to unstub because the time stub seems to carry across scenarios.

Has anyone else had this issue, or know of any other way to decently 
handle present time in cucumber?

Thanks,
Will


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.lrug.org/pipermail/chat-lrug.org/attachments/20100802/acf58f26/attachment.html>


More information about the Chat mailing list