ruby-on-rails - 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 而爆炸。
解决方案
可以这样做
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
推荐阅读
- awk - 如何在特定模式之后在换行符之间使用 sed 或 awk 进行提取?
- virtual-machine - 在 VMware 上的 Windows 10 和 Ubuntu 之间拖放文件和文件夹
- ruby - 我正在尝试为我的程序编写条件
- java - 范围“步骤”对于当前线程无效;如果您打算从单例中引用它,请考虑为此 bean 定义一个作用域代理
- reactjs - react-materialize DatePicker 初始化时允许空日期
- java - 处理 FFMPEG 视频时出现问题,输出视频在前 3 秒内全黑
- python - PySide Qt self.function 在 clicked.connect() 中不起作用
- javascript - 数据属性已更改但未应用
- json - 如何开始使用 .json 文件在外部读取和写入变量?
- netlogo - 如何在 netlogo 中询问海龟补丁