diff --git a/app/controllers/spree/credit_cards_controller.rb b/app/controllers/spree/credit_cards_controller.rb index 6a94dbdd7e..af52f171fb 100644 --- a/app/controllers/spree/credit_cards_controller.rb +++ b/app/controllers/spree/credit_cards_controller.rb @@ -1,5 +1,7 @@ # frozen_string_literal: true +require 'stripe/credit_card_remover' + module Spree class CreditCardsController < BaseController def new_from_token diff --git a/app/services/stripe/credit_card_remover.rb b/lib/stripe/credit_card_remover.rb similarity index 79% rename from app/services/stripe/credit_card_remover.rb rename to lib/stripe/credit_card_remover.rb index 9d691f2dab..7d665c92de 100644 --- a/app/services/stripe/credit_card_remover.rb +++ b/lib/stripe/credit_card_remover.rb @@ -10,11 +10,8 @@ module Stripe def call Stripe::CreditCardCloneDestroyer.new.destroy_clones(@credit_card) - stripe_customer = Stripe::Customer.retrieve(@credit_card.gateway_customer_profile_id, {}) - return unless stripe_customer - - stripe_customer.delete unless stripe_customer.deleted? + stripe_customer.delete if stripe_customer && !stripe_customer.deleted? end end end diff --git a/spec/lib/stripe/credit_card_remover_spec.rb b/spec/lib/stripe/credit_card_remover_spec.rb new file mode 100644 index 0000000000..91e130afb3 --- /dev/null +++ b/spec/lib/stripe/credit_card_remover_spec.rb @@ -0,0 +1,47 @@ +# frozen_string_literal: false + +require 'spec_helper' +require 'stripe/credit_card_remover' + +describe Stripe::CreditCardRemover do + let(:credit_card) { double('credit_card', gateway_customer_profile_id: 1) } + + context 'Stripe customer exists' do + context 'and is not deleted' do + it 'deletes the credit card clone and the customer' do + customer = double('customer', deleted?: false) + allow(Stripe::Customer).to receive(:retrieve).and_return(customer) + + expect_any_instance_of(Stripe::CreditCardCloneDestroyer).to receive(:destroy_clones).with( + credit_card + ) + expect(customer).to receive(:delete) + Stripe::CreditCardRemover.new(credit_card).call + end + end + + context 'and is deleted' do + it 'deletes the credit card clone' do + customer = double('customer', deleted?: true) + allow(Stripe::Customer).to receive(:retrieve).and_return(customer) + + expect_any_instance_of(Stripe::CreditCardCloneDestroyer).to receive(:destroy_clones).with( + credit_card + ) + expect(customer).not_to receive(:delete) + Stripe::CreditCardRemover.new(credit_card).call + end + end + end + + context 'Stripe customer does not exist' do + it 'deletes the credit card clone' do + allow(Stripe::Customer).to receive(:retrieve).and_return(nil) + + expect_any_instance_of(Stripe::CreditCardCloneDestroyer).to receive(:destroy_clones).with( + credit_card + ) + Stripe::CreditCardRemover.new(credit_card).call + end + end +end