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而崩溃。

您应该能够对这个使用Rspec复合预期

https://relishapp.com/rspec/rspec-expectations/docs/compound-expectations

所以我会把你的期望改写成这样:

expect { handler.call }.
to raise_error(FailedPaymentError).
and change { Subscription.count }.by(1)

可以像这样完成

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

相关内容

最新更新