RSpec检查是否已调用方法



我有一个AccountsControllerdestroy操作。我想测试帐户是否被删除以及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,所以它显示了这一点。如何修复此测试?

您需要将控制器上下文中的帐户实体替换为测试中的帐户

可能是

describe "#destroy" do
let(:account) { create(:account) }

it "deletes the account and cancels the subscription" do
allow(Current).to receive(:account).and_return(account)
# if the subscription does not exist in the context of the account  
# then you should stub or create it...
expect do
delete accounts_path
end.to change(Account, :count).by(-1)
expect(account.subscription).to have_received(:cancel_now!)
end
end

关于订阅

expect(account).to receive(:subscription).and_return(instance_double(Subscription))
# or
receive(:subscription).and_return(double('some subscription'))
# or
create(:subscription, account: account)
# or
account.subscription = create(:subscription)
# or other options ...

相关内容

  • 没有找到相关文章

最新更新