0

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

Sergei Struk
  • 358
  • 4
  • 12
  • Prove that `Time.now` is not changing and `created_at` is changing. You have not proven that, just made the assumption. In your script do a `puts Time.now` and `user.reload.created_at`. – Beartech Mar 19 '15 at 16:11
  • Unfortunately it is a common case - it has nothing to do with a stubbed time - it is the value of `created_at` which actually changes. Database do not store milliseconds, hence this information is lost after reload. Unfortunately I haven't seen a good solution for this problem yet. – BroiSatse Mar 19 '15 at 16:11
  • I get 60.0 for both--using rails 4.2.0, ruby 2.2.0, and rspec 2.14.1, and I get an error for `Time.stubs`, so there's something fishy with your output. – 7stud Mar 19 '15 at 18:15

1 Answers1

3

Just reset nanoseconds:

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

or milliseconds:

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

Here details.

Community
  • 1
  • 1
Maxim
  • 9,701
  • 5
  • 60
  • 108