DEV: Fix flaky test due to ActiveRecord query caching (#24476)

Why this change?

The test was randomly failing in
https://github.com/discourse/discourse/actions/runs/6936264158/job/18868087113
with the following failure:

```
expect do user.update_ip_address!("127.0.0.1") end.to change {
  UserIpAddressHistory.where(user_id: user.id).count
}.by(1)

expected `UserIpAddressHistory.where(user_id: user.id).count` to have changed by 1, but was changed by 0
```

This is due to the fact that ActiveRecord will actually cache the result
of `UserIpAddressHistory.where(user_id: user.id).count`. However,
`User.update_ip_address!` relies on mini_sql and does not go through
ActiveRecord. As a result, the query cache is not cleared and hence the
flakiness.

What does this change do?

This change uses the `uncached` method provided by ActiveRecord when
we are fetching the count.
This commit is contained in:
Alan Guo Xiang Tan 2023-11-21 14:03:19 +08:00 committed by GitHub
parent e37fb3042d
commit 1510e1d1ea
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 4 additions and 4 deletions

View File

@ -3048,19 +3048,19 @@ RSpec.describe User do
it "tracks old user record correctly" do
expect do user.update_ip_address!("127.0.0.1") end.to change {
UserIpAddressHistory.where(user_id: user.id).count
UserIpAddressHistory.uncached { UserIpAddressHistory.where(user_id: user.id).count }
}.by(1)
freeze_time 10.minutes.from_now
expect do user.update_ip_address!("0.0.0.0") end.to change {
UserIpAddressHistory.where(user_id: user.id).count
UserIpAddressHistory.uncached { UserIpAddressHistory.where(user_id: user.id).count }
}.by(1)
freeze_time 11.minutes.from_now
expect do user.update_ip_address!("127.0.0.1") end.to_not change {
UserIpAddressHistory.where(user_id: user.id).count
UserIpAddressHistory.uncached { UserIpAddressHistory.where(user_id: user.id).count }
}
expect(
@ -3070,7 +3070,7 @@ RSpec.describe User do
freeze_time 12.minutes.from_now
expect do user.update_ip_address!("0.0.0.1") end.not_to change {
UserIpAddressHistory.where(user_id: user.id).count
UserIpAddressHistory.uncached { UserIpAddressHistory.where(user_id: user.id).count }
}
expect(UserIpAddressHistory.where(user_id: user.id).pluck(:ip_address).map(&:to_s)).to eq(