Search code examples
ruby-on-railsrubyrspecrspec2

Changing of difference between created_at and frozen Time.now after reloading of object


I have spec which checks calculation of difference between Time.now and created_at attribute of object. I stubbed Time.now, so this value is constant. Also I've set Time.now to created_at, but this value changes after reloading of object. How is it possible and how can I freeze created_at after object reloading?

This is an example of issue:

time = Time.now
=> 2015-03-19 15:50:13 UTC
Time.stubs :now => time
=> #<Expectation:0x9938830 allowed any number of times...
user = User.last
=> #<User:0x000000097a6e40...
user.update_attribute :created_at, Time.now - 1.minute
=> true
user.created_at
=> Thu, 19 Mar 2015 15:49:13 UTC +00:00
Time.now - user.created_at
=> 60.0
Time.now - user.reload.created_at
=> 60.442063277

I use rails 4.2.0, ruby 2.2.0 and rspec 2.14.1


Solution

  • Just reset nanoseconds:

    time = Time.now.change(nsec: 0)
    

    or milliseconds:

    time = Time.now.change(usec: 0)
    

    Here details.