首页 > 解决方案 > Rspec:如何测试引发错误的方法

问题描述

我有一个带有调用方法的 SubscriptionHandler 类,该方法创建一个挂起的订阅,尝试向用户计费,然后在计费失败时出错。无论计费是否失败,都会创建挂起的订阅

class SubscriptionHandler

  def initialize(customer, stripe_token)
    @customer = customer
    @stripe_token = stripe_token
  end

  def call
    create_pending_subscription
    attempt_charge!
    upgrade_subscription
  end

  private

  attr_reader :stripe_token, :customer

  def create_pending_subscription
   @subscription = Subscription.create(pending: true, customer_id: customer.id)
  end

  def attempt_charge!
    StripeCharger.new(stripe_token).charge!  #raises FailedPaymentError
  end

  def upgrade_subscription
   @subscription.update(pending: true)
  end

 end

这是我的规格的样子:

describe SubscriptionHandler do

  describe "#call" do
    it "creates a pending subscription" do
      customer = create(:customer)
      token = "token-xxx"
      charger = StripeCharger.new(token)
      allow(StripeCharger).to receive(:new).and_return(charger)
      allow(charger).to receive(:charge!).and_raise(FailedPaymentError)
      handler = SubscriptionHandler.new(customer, token)

      expect { handler.call }.to change { Subscription.count }.by(1) # Fails with FailedPaymentError
    end
  end
end

但这不会改变订阅计数,它会因 FailedPaymentError 而失败。有没有办法检查订阅数量是否增加,而规范不会因 FailedPaymentError 而爆炸。

标签: ruby-on-railsrspec

解决方案


可以这样做

expect{ handler.call }.to raise_error FailedPaymentError

应该管用。

如果您根本不想引发错误,则可以删除此行,并返回有效响应

allow(charger).to receive(:charge!).and_raise(FailedPaymentError)

更多信息 -如何在 Rails/RSpec 中测试异常引发?

官方 RSpec 文档

https://relishapp.com/rspec/rspec-expectations/v/2-0/docs/matchers/expect-error


推荐阅读