diff --git a/app/models/registration.rb b/app/models/registration.rb index 2f2d5c68..d02fa8bb 100644 --- a/app/models/registration.rb +++ b/app/models/registration.rb @@ -29,6 +29,7 @@ class Registration < ActiveRecord::Base validate :registration_limit_not_exceed, on: :create after_create :set_week, :subscribe_to_conference, :send_registration_mail + after_destroy :destroy_purchased_tickets def week created_at.strftime('%W').to_i @@ -36,6 +37,11 @@ class Registration < ActiveRecord::Base private + def destroy_purchased_tickets + ticket_purchased = TicketPurchase.where(conference_id: conference_id, user_id: user.id) + ticket_purchased.destroy_all + end + def subscribe_to_conference Subscription.create(conference_id: conference.id, user_id: user.id) end diff --git a/spec/models/registration_spec.rb b/spec/models/registration_spec.rb index 1bf9e88f..665b4e4b 100644 --- a/spec/models/registration_spec.rb +++ b/spec/models/registration_spec.rb @@ -3,6 +3,10 @@ require 'spec_helper' describe 'Registration' do + + let!(:user) { create(:user) } + let!(:conference) { create(:conference) } + let!(:registration1) { create(:registration, conference: conference, user: user) } describe 'validations' do it 'has a valid factory' do expect(build(:registration)).to be_valid @@ -10,16 +14,28 @@ describe 'Registration' do describe 'registration_limit_not_exceed' do it 'is not valid when limit exceeded' do - conference = build(:conference) conference.registration_limit = 1 - registration1 = build(:registration, conference: conference) - registration1.save - registration2 = build(:registration, conference: conference) - registration2.save - expect(conference.registrations.size).to be 1 - expect(registration2.valid?).to be false - expect(registration2.errors.full_messages).to eq(['Registration limit exceeded']) + expect { create(:registration, conference: conference, user: user) }.to raise_error + expect(user.registrations.size).to be 1 end end end + + describe '#destroy_purchased_tickets' do + it 'destroys purchased tickets if tickets are purchased' do + create(:ticket_purchase, conference: conference, user: user) + expect(user.registrations.size).to be 1 + expect(user.ticket_purchases.size).to be 1 + registration1.destroy + expect(user.registrations.size).to be 0 + expect(user.ticket_purchases.size).to be 0 + end + it 'destroys no tickets if no tickets are purchased' do + expect(user.registrations.size).to be 1 + expect(user.ticket_purchases.size).to be 0 + registration1.destroy + expect(user.registrations.size).to be 0 + expect(user.ticket_purchases.size).to be 0 + end + end end