Trouble comparing time with RSpec Trouble comparing time with RSpec ruby ruby

Trouble comparing time with RSpec


I find using the be_within default rspec matcher more elegant:

expect(@article.updated_at.utc).to be_within(1.second).of Time.now


Ruby Time object maintains greater precision than the database does. When the value is read back from the database, it’s only preserved to microsecond precision, while the in-memory representation is precise to nanoseconds.

If you don't care about millisecond difference, you could do a to_s/to_i on both sides of your expectation

expect(@article.updated_at.utc.to_s).to eq(Time.now.to_s)

or

expect(@article.updated_at.utc.to_i).to eq(Time.now.to_i)

Refer to this for more information about why the times are different


Old post, but I hope it helps anyone who enters here for a solution. I think it's easier and more reliable to just create the date manually:

it "updates updated_at attribute" do  freezed_time = Time.utc(2015, 1, 1, 12, 0, 0) #Put here any time you want  Timecop.freeze(freezed_time) do    patch :update    @article.reload    expect(@article.updated_at).to eq(freezed_time)  endend

This ensures the stored date is the right one, without doing to_x or worrying about decimals.