I am create a variable @now to keep the value lets say '2023-01-04T14:30:00-04:00' but the time is not the same, i believe that is recalculating mseconds
it 'ok' do
@now = DateTime.now
payload = {
start: @now
}
put "/api/v1/#{@id}", params: payload
expect(@element.start).to eq(@now)
i am getting this error
Diff:
@@ -1 1 @@
-Wed, 04 Jan 2023 15:23:39 0000
Wed, 04 Jan 2023 15:23:38.324000000 UTC 00:00
CodePudding user response:
whenever you test something related with Date or Time, it is a very good practice (if not the only) to freeze the time as shown in the previous answer.
It is the only way to guarantee the same timing result no matter when you run the test. Id suggest you to looking into date/time testing scenarios and how ActiveSupport::Testing::TimeHelpers
is used.
CodePudding user response:
You're almost certainly making the classic beginner mistake of confusing the instance variables of your test/spec with those that exist in the controller.
They belong to a completely different class and are quite often running in a completely different process. ActiveRecord models don't have a "live" database connection and are just a snapshot of the data when it was queried.
If you want to see changes performed in the controller reflected in your tests you need to refresh the attributes of the model with a database query:
it 'updates the starting time' do
payload = {
start: Time.at(0)
}
expect {
put "/api/v1/#{@id}", params: payload
@element.reload
}.to_change(@element, :start).to be_within(1.second).of(payload[:start])
end
To make these kinds of errors more obvious its often useful to use times in your tests that are way off from the current time (like the start of unix time) so that you don't end up with a false positive caused by a time thats a few miliseconds off.