FIX: "confirm new email" emails were failing for EmailChangeRequest records with blank requested_by_user_id field (#12579)

FIX: “confirm new email” emails were failing for EmailChangeRequest records with blank requested_by_user_id field (#12579)

diff --git a/app/models/email_change_request.rb b/app/models/email_change_request.rb
index be1448f..60b0d04 100644
--- a/app/models/email_change_request.rb
+++ b/app/models/email_change_request.rb
@@ -13,7 +13,7 @@ class EmailChangeRequest < ActiveRecord::Base
   end
 
   def requested_by_admin?
-    self.requested_by.admin? && !self.requested_by_self?
+    self.requested_by&.admin? && !self.requested_by_self?
   end
 
   def requested_by_self?
diff --git a/spec/jobs/user_email_spec.rb b/spec/jobs/user_email_spec.rb
index b941560..c91ed8e 100644
--- a/spec/jobs/user_email_spec.rb
+++ b/spec/jobs/user_email_spec.rb
@@ -321,6 +321,15 @@ describe Jobs::UserEmail do
           expect(mail.body).not_to include("This email change was requested by a site admin.")
         end
       end
+
+      context "when requested_by record is not present" do
+        let(:requested_by) { nil }
+        it "passes along false for the requested_by_admin param which changes the wording in the email" do
+          Jobs::UserEmail.new.execute(type: :confirm_new_email, user_id: user.id, email_token: email_token.token)
+          mail = ActionMailer::Base.deliveries.first
+          expect(mail.body).not_to include("This email change was requested by a site admin.")
+        end
+      end
     end
 
     context "post" do

GitHub sha: 3db08c07

This commit appears in #12579 which was approved by ZogStriP. It was merged by techAPJ.