diff --git a/app/controllers/alaveteli_pro/stripe_webhooks_controller.rb b/app/controllers/alaveteli_pro/stripe_webhooks_controller.rb index dcd37f74a3..46ed5bfb9b 100644 --- a/app/controllers/alaveteli_pro/stripe_webhooks_controller.rb +++ b/app/controllers/alaveteli_pro/stripe_webhooks_controller.rb @@ -70,7 +70,7 @@ def invoice_payment_succeeded def invoice_payment_failed account = pro_account_from_stripe_event(@stripe_event) - return unless account + return unless account&.subscription? AlaveteliPro::SubscriptionMailer.payment_failed(account.user).deliver_now end diff --git a/spec/controllers/alaveteli_pro/stripe_webhooks_controller_spec.rb b/spec/controllers/alaveteli_pro/stripe_webhooks_controller_spec.rb index f79b62c672..ebb3c2cf0b 100644 --- a/spec/controllers/alaveteli_pro/stripe_webhooks_controller_spec.rb +++ b/spec/controllers/alaveteli_pro/stripe_webhooks_controller_spec.rb @@ -255,25 +255,44 @@ def send_request StripeMock.mock_webhook_event('invoice.payment_failed') end - let!(:user) do - user = FactoryBot.create(:pro_user) - user.pro_account.stripe_customer_id = stripe_event.data.object.customer - user.pro_account.save! - user + let(:customer_id) { stripe_event.data.object.customer } + + let(:pro_account) do + FactoryBot.create(:pro_account, stripe_customer_id: customer_id) end before do - send_request + allow(ProAccount).to receive(:find_by). + with(stripe_customer_id: customer_id).and_return(pro_account) end it 'handles the event' do expect(response.status).to eq(200) end - it 'notifies the user that their payment failed' do - mail = ActionMailer::Base.deliveries.first - expect(mail.subject).to match(/Payment failed/) - expect(mail.to).to include(user.email) + context 'the user has a subscription' do + before do + allow(pro_account).to receive(:subscription?).and_return(true) + send_request + end + + it 'notifies the user that their payment failed' do + mail = ActionMailer::Base.deliveries.first + expect(mail.subject).to match(/Payment failed/) + expect(mail.to).to include(pro_account.user.email) + end + end + + context 'the user does not have a subscription' do + before do + allow(pro_account).to receive(:subscription?).and_return(false) + send_request + end + + it 'does not notify the user that their payment failed' do + mail = ActionMailer::Base.deliveries.first + expect(mail).to be_nil + end end end