From 37b71c5903f338ef19ac4e6e6d76daf31d81cc8a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Guitaut?= Date: Wed, 24 May 2023 11:08:56 +0200 Subject: [PATCH] =?UTF-8?q?FIX:=20Don=E2=80=99t=20run=20validations=20when?= =?UTF-8?q?=20invalidating=20invites?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This patch is a followup of https://github.com/discourse/discourse/pull/21504 where limits on custom message for an invite were introduced. This had a side effect of making some existing invites invalid and with the current code, they can’t be invalidated anymore. This patch takes the approach of skipping the validations when invites are invalidated since the important thing here is to mark the invite as invalidated regardless of its actual state in the DB. (no other attributes are updated at the same time anyway) --- app/models/invite.rb | 8 +++++--- spec/models/invite_spec.rb | 27 ++++++++++++++++++++++++++- 2 files changed, 31 insertions(+), 4 deletions(-) diff --git a/app/models/invite.rb b/app/models/invite.rb index 66697d34dfb..191da0818ca 100644 --- a/app/models/invite.rb +++ b/app/models/invite.rb @@ -274,10 +274,12 @@ class Invite < ActiveRecord::Base end def self.invalidate_for_email(email) - invite = Invite.find_by(email: Email.downcase(email)) - invite.update!(invalidated_at: Time.zone.now) if invite + Invite.find_by(email: Email.downcase(email))&.invalidate! + end - invite + def invalidate! + update_attribute(:invalidated_at, Time.current) + self end def resend_invite diff --git a/spec/models/invite_spec.rb b/spec/models/invite_spec.rb index d467b30e8f4..e93f09561a1 100644 --- a/spec/models/invite_spec.rb +++ b/spec/models/invite_spec.rb @@ -478,7 +478,7 @@ RSpec.describe Invite do end end - describe "#invalidate_for_email" do + describe ".invalidate_for_email" do it "returns nil if there is no invite for the given email" do invite = Invite.invalidate_for_email("test@example.com") expect(invite).to eq(nil) @@ -600,4 +600,29 @@ RSpec.describe Invite do end end end + + describe "#invalidate!" do + subject(:invalidate) { invite.invalidate! } + + fab!(:invite) { Fabricate(:invite) } + + before { freeze_time } + + it "invalidates the invite" do + expect { invalidate }.to change { invite.invalidated_at }.to Time.current + end + + it "returns the invite" do + expect(invalidate).to eq invite + end + + context "when the invite is in an invalid state" do + before { invite.update_attribute(:custom_message, "a" * 2000) } + + it "still invalidates the invite" do + expect(invite).to be_invalid + expect { invalidate }.to change { invite.invalidated_at }.to Time.current + end + end + end end