FIX: randomly failing user_spec (#9754)

FIX: randomly failing user_spec (#9754)

  • FIX: randomly falling user_spec

When we evaluate update_last_seen! we relay on Redis to not run that code too often

The problem is that not all specs which are running update_last_seen! are not cleaning after themselves

For examples specs in that block

So it can be replicated when you run a few times bundle exec rspec ./spec/models/user_spec.rb -e "should not update the first seen value if it doesn't exist" -e "should have 0 for days_visited"

We should delete Redis key after each spec which is evaluating update_last_seen!

diff --git a/spec/models/user_spec.rb b/spec/models/user_spec.rb
index bb27aa4..637e2fd 100644
--- a/spec/models/user_spec.rb
+++ b/spec/models/user_spec.rb
@@ -873,6 +873,10 @@ describe User do
       SiteSetting.previous_visit_timeout_hours = 1
+    after do
+      Discourse.redis.del("user:#{}:#{}")
+    end
     it "should act correctly" do
       expect(user.previous_visit_at).to eq(nil)
@@ -903,6 +907,10 @@ describe User do
     let!(:first_visit_date) { }
     let!(:second_visit_date) { 2.hours.from_now }
+    after do
+      Discourse.redis.del("user:#{}:#{}")
+    end
     it "should update the last seen value" do
       expect(user.last_seen_at).to eq nil
@@ -976,7 +984,9 @@ describe User do
     describe 'with no previous values' do
       after do
-        Discourse.redis.flushall
+        Discourse.redis.del("user:#{}:#{}")
+        unfreeze_time
+        Discourse.redis.del("user:#{}:#{}")
       it "updates last_seen_at" do
@@ -1305,6 +1315,9 @@ describe User do
       let!(:user) { Fabricate(:user) }
       let!(:now) { }
       before { user.update_last_seen!(now) }
+      after do
+        Discourse.redis.del("user:#{}:#{now.to_date}")
+      end
       it "with existing UserVisit record, increments the posts_read value" do
         expect {

GitHub sha: 65a3fdbc

This commit appears in #9754 which was merged by lis2.

You are repeating this code quite a bit. May I suggest to create a method user.reset_last_seen_cache! and then call that in your specs?

1 Like

Thank you for that suggestion. This method is very test specific so instead of moving that to the user model, I added the helper method at the bottom of the spec