File tree Expand file tree Collapse file tree 2 files changed +33
-1
lines changed Expand file tree Collapse file tree 2 files changed +33
-1
lines changed Original file line number Diff line number Diff line change @@ -9,7 +9,7 @@ and pairing with smart people at Hashrocket.
99
1010For a steady stream of TILs, [ sign up for my newsletter] ( https://tinyletter.com/jbranchaud ) .
1111
12- _ 895 TILs and counting..._
12+ _ 896 TILs and counting..._
1313
1414---
1515
@@ -527,6 +527,7 @@ _895 TILs and counting..._
527527- [ Change The Nullability Of A Column] ( rails/change-the-nullability-of-a-column.md )
528528- [ Check Specific Attributes On ActiveRecord Array] ( rails/check-specific-attributes-on-activerecord-array.md )
529529- [ Code Statistics For An Application] ( rails/code-statistics-for-an-application.md )
530+ - [ Comparing DateTimes Down To Second Precision] ( rails/comparing-datetimes-down-to-second-precision.md )
530531- [ Conditional Class Selectors in Haml] ( rails/conditional-class-selectors-in-haml.md )
531532- [ Convert A Symbol To A Constant] ( rails/convert-a-symbol-to-a-constant.md )
532533- [ Creating Records of Has_One Associations] ( rails/creating-records-of-has-one-associations.md )
Original file line number Diff line number Diff line change 1+ # Comparing DateTimes Down To Second Precision
2+
3+ You may have an RSpec test for your Rails codebase that asserts about the
4+ datetime a record gets saved with:
5+
6+ ``` ruby
7+ two_weeks_ago = 2 .weeks.ago
8+
9+ record = Thing .create(two_weeks_ago)
10+
11+ expect(record.some_date_time).to eq(two_weeks_ago)
12+ ```
13+
14+ This comparison happens with precision down to the nanosecond. Unfortunately,
15+ depending on your operating system and backing database, you may see
16+ inconsistent results due to variations in precision.
17+
18+ One way to deal with this, if you only care about precision down to the second,
19+ is to modify the expecationa little with the [ ` be_within `
20+ matcher] ( https://relishapp.com/rspec/rspec-expectations/docs/built-in-matchers/be-within-matcher ) .
21+
22+ ``` ruby
23+ two_weeks_ago = 2 .weeks.ago
24+
25+ record = Thing .create(two_weeks_ago)
26+
27+ expect(record.some_date_time).to be_within(1 .second).of(two_weeks_ago)
28+ ```
29+
30+ The ` be_within ` matcher can also be used as [ a nested
31+ matcher] ( https://twitter.com/jbrancha/status/1213162124777869319?s=20 ) .
You can’t perform that action at this time.
0 commit comments