[rspec-users] stubbing Time.zone.now for model tests fails for Rails 2.3.1
dchelimsky at gmail.com
Wed Mar 11 13:57:57 EDT 2009
On Wed, Mar 11, 2009 at 12:40 PM, David Schmidt <davids at tower-mt.com> wrote:
> Our application has some code to schedule recurring tasks, with code to skip
> holidays and weekends.
> In order to test the schedule model we need to have a fixed time returned
> when the model is run so that the tests will run the same no matter what day
> they are run. (The first set of tests written would all pass until run on a
> weekend, when the skip code would schedule a task days later in order to
> skip a weekend day.)
> Our solution under Rails 2.1 was to set an instance variable to a fixed time
> and then to stub the time returned, similar to the method that David
> Chelimsky recommended:
> now = Time.now
> However, our app is using Time.zone.now in order to return local time in the
> user's local time zone. The following code works in Rails 2.1:
> @now = Time.now
> @timezone = TimeZone.new('UTC')
@now = Time.now
@zone = mock('timezone')
Now you're not depending on TimeZone in the examples. Let us know if it works.
> In Rails 2.1 this properly returned @now when the model accessed
> After upgrading to Rails 2.3.1 (and RSpec 220.127.116.11) *all* tests that use
> this method fail. They appear to fail as soon as a time from Time.zone.now
> is saved to a model and then accessed, even though the time in the record
> appears fine.
> The error we're getting is:
> "You have a nil object when you didn't expect it!
> The error occurred while evaluating nil.period_for_utc"
> If I comment out the last two lines above ("Time.stub!" and
> "@timezone.stub!") then I don't get that error, but without fixed times some
> of our tests fail due to the variable time.
> Has anyone else run into this problem and come up with a solution to getting
> a fixed time back from Time.zone.now?
> David Schmidt
> davids at tower-mt.com
> rspec-users mailing list
> rspec-users at rubyforge.org
More information about the rspec-users