We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
Testing DateTime Equality in Elixir Tests
amos-kibet
Created
Ever run into flaky tests when comparing timestamps? Here’s a common scenario:
date_time_now = DateTime.utc_now() |> DateTime.truncate(:second)
assert DateTime.truncate(your_record_timestamp, :second) == date_time_now
The failure:
Assertion with == failed
code: assert DateTime.truncate(your_record_timestamp, :second) == date_time_now
left: ~U[2024-11-19 07:56:53Z]
right: ~U[2024-11-19 07:56:54Z]
Even with truncated seconds, you might still get failures due to the tiny delay between timestamp creation and database operations.
💡 Solution: Use assert_in_delta
instead, and allow a reasonable time delta:
assert_in_delta DateTime.to_unix(your_record_timestamp),
DateTime.to_unix(now),
1
More reliable, less headaches! Read more about assert_in_delta
here: https://hexdocs.pm/ex_unit/ExUnit.Assertions.html#assert_in_delta/4:~:text=to%20this%20function-,assert_in_delta,-(value1%2C%20value2%2C%20delta
Copy link
copied to clipboard