FIX: do not log username change if the save process was unsuccessful

FIX: do not log username change if the save process was unsuccessful

diff --git a/app/services/username_changer.rb b/app/services/username_changer.rb
index 287360e..6b23d3e 100644
--- a/app/services/username_changer.rb
+++ b/app/services/username_changer.rb
@@ -16,13 +16,13 @@ class UsernameChanger
   end
 
   def change(asynchronous: true, run_update_job: true)
-    if @actor && @old_username != @new_username
-      StaffActionLogger.new(@actor).log_username_change(@user, @old_username, @new_username)
-    end
-
     @user.username = @new_username
 
     if @user.save
+      if @actor && @old_username != @new_username
+        StaffActionLogger.new(@actor).log_username_change(@user, @old_username, @new_username)
+      end
+
       UsernameChanger.update_username(user_id: @user.id,
                                       old_username: @old_username,
                                       new_username: @new_username,
diff --git a/spec/services/username_changer_spec.rb b/spec/services/username_changer_spec.rb
index 7f4346c..a2bd262 100644
--- a/spec/services/username_changer_spec.rb
+++ b/spec/services/username_changer_spec.rb
@@ -56,6 +56,10 @@ describe UsernameChanger do
         expect do
           UsernameChanger.change(myself, "HanSolo", myself)
         end.to change { UserHistory.count }.by(0) # make sure it does not log a dupe
+
+        expect do
+          UsernameChanger.change(myself, user.username, myself)
+        end.to change { UserHistory.count }.by(0) # does not log if the username already exists
       end
     end

GitHub sha: a2b1789c

1 Like

This commit has been mentioned on Discourse Meta. There might be relevant details there: