gpt4 book ai didi

ruby-on-rails - Rspec:如何测试引发错误的方法

转载 作者:行者123 更新时间:2023-12-02 04:20:23 24 4
gpt4 key购买 nike

我有一个 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)

关于ruby-on-rails - Rspec:如何测试引发错误的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60423433/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com