RSpec 检查方法是否被调用

RSpec check if method has been called

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