【发布时间】:2021-09-12 19:22:50
【问题描述】:
我有一个AccountsController 和一个destroy 操作。我想测试帐户是否被删除以及subscription 是否被取消。
AccountsController
def destroy
Current.account.subscription&.cancel_now!
Current.account.destroy
end
RSpec
describe "#destroy" do
let(:account) { create(:account) }
it "deletes the account and cancels the subscription" do
allow(account).to receive(:subscription)
expect do
delete accounts_path
end.to change(Account, :count).by(-1)
expect(account.subscription).to have_received(:cancel_now!)
end
end
但是上面的测试没有通过。它说,
(nil).cancel_now!
expected: 1 time with any arguments
received: 0 times with any arguments
因为account.subscription 返回nil 它显示了这一点。如何修复此测试?
【问题讨论】:
-
您的意思是
expect to have_received?不确定allow to have_received是否会生成此消息。 -
您会收到此消息,因为您的控制器中的
Current.account与您的规范中的let(:account)没有任何关系。您对一件事设定期望,但使用另一件事。
标签: ruby-on-rails ruby rspec rspec-rails