From 57e7172af9cb150c0831c23eb0fd4e945d31c28e Mon Sep 17 00:00:00 2001 From: "James R. Griffin III" <1443986+jrgriffiniii@users.noreply.github.com> Date: Thu, 26 Sep 2024 11:03:45 -0400 Subject: [PATCH] Ensuring that ActiveModel errors result in one retry for Group#default_user (#1950) --- app/models/group.rb | 15 ++++++++++++--- spec/models/group_spec.rb | 18 ++++++++++++++++++ 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/app/models/group.rb b/app/models/group.rb index 6c0a52589..4b50b836b 100644 --- a/app/models/group.rb +++ b/app/models/group.rb @@ -208,9 +208,18 @@ def default_user(uid) user = User.find_by(uid:) return user if user.present? - user = User.new(uid:, default_group_id: id) - user.save! - user + begin + user = User.new(uid:, default_group_id: id) + user.save! + user + rescue ActiveRecord::RecordNotUnique => unique_error + # If adding a submitter to an existing group + Rails.logger.error("Failed to created a new user for #{self}: #{unique_error}") + user = User.new(uid:) + user.default_group_id = id + user.save! + user + end end end # rubocop:enable Metrics/ClassLength diff --git a/spec/models/group_spec.rb b/spec/models/group_spec.rb index 5554e18a1..007b641d6 100644 --- a/spec/models/group_spec.rb +++ b/spec/models/group_spec.rb @@ -143,5 +143,23 @@ Group.plasma_laboratory.default_user("abc123") expect(user.reload.default_group).to eq(Group.research_data) end + + context "when an error is encountered while persisting the user model" do + let(:user) { FactoryBot.build(:user) } + let(:uid) { "abc234" } + let(:default_group_id) { Group.plasma_laboratory.id } + + before do + user + allow(User).to receive(:new).with(uid:, default_group_id:).and_raise(ActiveRecord::RecordNotUnique) + allow(User).to receive(:new).with(uid:).and_return(user) + end + + it "attempts to create a new user mode without initially setting the default group ID" do + persisted = Group.plasma_laboratory.default_user("abc234") + + expect(persisted.default_group_id).to eq(Group.plasma_laboratory.id) + end + end end end