diff --git a/app/models/spree/user_decorator.rb b/app/models/spree/user_decorator.rb index 7ee42af088..9890d0ff7b 100644 --- a/app/models/spree/user_decorator.rb +++ b/app/models/spree/user_decorator.rb @@ -9,6 +9,8 @@ Spree.user_class.class_eval do attr_accessible :enterprise_ids, :enterprise_roles_attributes after_create :send_signup_confirmation + validate :owned_enterprises_count + def build_enterprise_roles Enterprise.all.each do |enterprise| unless self.enterprise_roles.find_by_enterprise_id enterprise.id @@ -20,4 +22,12 @@ Spree.user_class.class_eval do def send_signup_confirmation Spree::UserMailer.signup_confirmation(self).deliver end + + private + + def owned_enterprises_count + if owned_enterprises.size > enterprise_limit + errors.add(:owned_enterprises, "^The nominated user is not permitted to own own any more enterprises.") + end + end end diff --git a/spec/models/spree/user_spec.rb b/spec/models/spree/user_spec.rb index 166ae6dab5..e985d9bde8 100644 --- a/spec/models/spree/user_spec.rb +++ b/spec/models/spree/user_spec.rb @@ -3,17 +3,28 @@ describe Spree.user_class do it { should have_many(:owned_enterprises) } describe "enterprise ownership" do - let(:u) { create(:user) } - let(:e1) { create(:enterprise, owner: u) } - let(:e2) { create(:enterprise, owner: u) } + let(:u1) { create(:user) } + let(:u2) { create(:user) } + let(:e1) { create(:enterprise, owner: u1) } + let(:e2) { create(:enterprise, owner: u1) } + it "provides access to owned enteprises" do - expect(u.owned_enterprises).to include e1, e2 + expect(u1.owned_enterprises).to include e1, e2 + end + + it "enforces the limit on the number of enterprise owned" do + expect(u2.owned_enterprises).to eq [] + u2.owned_enterprises << e1 + u2.owned_enterprises << e2 + expect { + u2.save! + }.to raise_error ActiveRecord::RecordInvalid, "Validation failed: The nominated user is not permitted to own own any more enterprises." + end end end context "#create" do - it "should send a signup email" do Spree::UserMailer.should_receive(:signup_confirmation).and_return(double(:deliver => true)) create(:user)