Как проверить случай сбоя полосы с rspecs? - PullRequest
0 голосов
/ 06 сентября 2018

У меня есть следующая конечная точка в контроллере платежей, которая завершает покупку. Я использую rspecs для тестирования. Для насмешливой полосы я использую драгоценный камень webmock. Теперь я хотел бы проверить случай сбоя, т.е. спасти Stripe :: CardError => e часть. Я прокомментировал ниже # Дело об отказе.

   def create

    @cart.user = current_user

    customer = Stripe::Customer.create email: stripe_params['sender_email'],
                                       source: stripe_params["card_token"]

    Stripe::Charge.create customer: customer.id,
                          amount: @cart.subtotal,
                          description: 'Gift Purchase',
                          currency: 'usd'

    render "confirmation"

   rescue Stripe::CardError => e
     #Failure Case
     flash[:alert] = e.message
     redirect_to new_payment_path
   end

Мой тестовый пример rspecs выглядит следующим образом. Сначала я заглушаю веб-запрос, используемый Stripe. Как я должен заглушить запрос, чтобы полоса выдавала исключение Stripe :: CardError и выполнялась ветка сбоя. Надеюсь, я прояснил проблему. Я ценю любую помощь. Спасибо!

 context "invalid purchases" do 

   it "card error" do

       stub_request(:post, "https://api.stripe.com/v1/customers").
         with(
           body: {"email"=>"asd@asd.com"},
           headers: {
          'Accept'=>'*/*',
          'Accept-Encoding'=>'gzip;q=1.0,deflate;q=0.6,identity;q=0.3',
          'Authorization'=>'Bearer sk_test_UEBAIinq8viQ875czrsC18ZX',
          'Content-Type'=>'application/x-www-form-urlencoded',
          'User-Agent'=>'Stripe/v1 RubyBindings/3.17.0',
          'X-Stripe-Client-User-Agent'=>'{"bindings_version":"3.17.0","lang":"ruby","lang_version":"2.3.4 p301 (2017-03-30)","platform":"x86_64-linux","engine":"ruby","publisher":"stripe","uname":"Linux version 4.9.120-c9 (root@b1cff69ce3c3) (gcc version 8.2.0 (Debian 8.2.0-4) ) #1 SMP Wed Aug 15 22:48:26 UTC 2018","hostname":"kofhearts-ktmbasket-6224565"}'
           }).
         to_return(status: 200, body: {id: 1}.to_json, headers: {})




     stub_request(:post, "https://api.stripe.com/v1/charges").
         with(
           body: {"amount"=>"123", "currency"=>"usd", "customer"=>"1", "description"=>"Gift Purchase"},
           headers: {
          'Accept'=>'*/*',
          'Accept-Encoding'=>'gzip;q=1.0,deflate;q=0.6,identity;q=0.3',
          'Authorization'=>'Bearer sk_test_UEBAIinq8viQ875czrsC18ZX',
          'Content-Type'=>'application/x-www-form-urlencoded',
          'User-Agent'=>'Stripe/v1 RubyBindings/3.17.0',
          'X-Stripe-Client-User-Agent'=>'{"bindings_version":"3.17.0","lang":"ruby","lang_version":"2.3.4 p301 (2017-03-30)","platform":"x86_64-linux","engine":"ruby","publisher":"stripe","uname":"Linux version 4.9.120-c9 (root@b1cff69ce3c3) (gcc version 8.2.0 (Debian 8.2.0-4) ) #1 SMP Wed Aug 15 22:48:26 UTC 2018","hostname":"kofhearts-ktmbasket-6224565"}'
           }).
         to_return(status: 200, body: {id: 1}.to_json, headers: {})



      visit root_path

      expect(page).to have_content('teddy')
      click_button('Add to Basket')
      expect(page).to have_content('Your Basket')
      click_link('Checkout')
      click_link('Guest Checkout')

      find('label', :text => 'Credit Card').click
      fill_in 'card_number', with: '4242424242424242'
      fill_in 'card_verification', with: '123'
      fill_in 'exp_month', with: '12'
      fill_in 'exp_year', with: '19'

      click_button('Submit')



   end

 end

1 Ответ

0 голосов
/ 06 сентября 2018

Для ошибок с поддельными картами, и вы можете найти больше примеров здесь

it "mocks a declined card error" do
  # Prepares an error for the next create charge request
  StripeMock.prepare_card_error(:card_declined)

  expect { Stripe::Charge.create(amount: 1, currency: 'usd') }.to raise_error {|e|
    expect(e).to be_a Stripe::CardError
    expect(e.http_status).to eq(402)
    expect(e.code).to eq('card_declined')
  }
end
...