diff --git a/app/models/user.rb b/app/models/user.rb index 4384bc495..175657cba 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -7,9 +7,9 @@ class User < ApplicationRecord # Marked as optional because we validate organisation_id below instead so that # the error message is linked to the right field on the form belongs_to :organisation, optional: true - has_many :owned_lettings_logs, through: :organisation, dependent: :delete_all + has_many :owned_lettings_logs, through: :organisation has_many :managed_lettings_logs, through: :organisation - has_many :owned_sales_logs, through: :organisation, dependent: :delete_all + has_many :owned_sales_logs, through: :organisation has_many :managed_sales_logs, through: :organisation validates :name, presence: true diff --git a/spec/models/user_spec.rb b/spec/models/user_spec.rb index 3fa6354a8..4038a9726 100644 --- a/spec/models/user_spec.rb +++ b/spec/models/user_spec.rb @@ -269,4 +269,37 @@ RSpec.describe User, type: :model do end end end + + describe "delete" do + let(:user) { FactoryBot.create(:user) } + let!(:owned_lettings_log) do + FactoryBot.create( + :lettings_log, + :completed, + owning_organisation: user.organisation, + managing_organisation: user.organisation, + created_by: user, + ) + end + + context "when the user is deleted" do + it "owned lettings logs are not deleted as a result" do + expect(described_class.count).to eq(1) + expect(LettingsLog.count).to eq(1) + user.destroy! + expect(described_class.count).to eq(0) + expect(LettingsLog.count).to eq(1) + end + + it "owned lettings logs are not deleted as a result" do + expect(described_class.count).to eq(1) + expect(LettingsLog.count).to eq(1) + expect(Organisation.count).to eq(1) + user.organisation.destroy! + expect(described_class.count).to eq(0) + expect(Organisation.count).to eq(0) + expect(LettingsLog.count).to eq(0) + end + end + end end