[rspec-users] Specs of code that use Time.now

Courtenay court3nay at gmail.com
Tue Feb 13 13:22:22 EST 2007


On 2/13/07, Ashley Moran <work at ashleymoran.me.uk> wrote:
> On 13 Feb 2007, at 16:15, Courtenay wrote:
>
> > Personally I like to put this in spec_helper
> >
> > def Time.now
> >   Time.local(2006,12,01,0,0,0)
> > end
> >
> > Then all dates are fixed (1 day from now is 2006-12-02 for example).
> > No clue if this is best practise, works well here though.
>
> Does this not interfere with RSpec?  I noticed it calling Time.now
> four times without any code on my part.  I suppose something has to
> give though
>

Try this:

class Foo
  class Time < ::Time
    def self.now
      Time.local(2006,10,1,0,0,0)
    end
  end

  def test_local
    Time.now.inspect
  end
end

f = Foo.new
f.test_local
=> "Sun Oct 01 00:00:00 -0700 2006"
Time.new
=> Tue Feb 13 10:14:03 -0800 2007

So, just make a new subclass of your model called Time that inherits
from ::Time but overrides the .now to fix the date, and it shouldn't
be that much of a problem :)


More information about the rspec-users mailing list