RSpec:如何测试方法是否被调用?

Mik*_*rth 103 ruby rspec ruby-on-rails

在编写RSpec测试时,我发现自己编写了大量看起来像这样的代码,以确保在执行测试期间调用一个方法(为了论证,我们只能说我不能真正地查询状态调用后的对象,因为该方法执行的操作不容易看到效果).

describe "#foo"
  it "should call 'bar' with appropriate arguments" do
    called_bar = false
    subject.stub(:bar).with("an argument I want") { called_bar = true }
    subject.foo
    expect(called_bar).to be_true
  end
end
Run Code Online (Sandbox Code Playgroud)

我想知道的是:有比这更好的语法吗?我是否缺少一些时髦的RSpec非常棒,可以将上面的代码减少到几行?should_receive听起来它应该这样做但是进一步阅读它听起来并不完全是它的作用.

wac*_*cko 133

it "should call 'bar' with appropriate arguments" do
  expect(subject).to receive(:bar).with("an argument I want")
  subject.foo
end
Run Code Online (Sandbox Code Playgroud)

  • @ ecoding5没有.它没有,也不应该检查`called_bar`.这只是一个确保方法被调用的标志,但是`expect(...).接收(...)`你已经覆盖了它.它更加清晰和语义 (2认同)

Uri*_*ssi 99

在新rspec expect语法中,这将是:

expect(subject).to receive(:bar).with("an argument I want")
Run Code Online (Sandbox Code Playgroud)


bjh*_*aid 34

以下应该有效

describe "#foo"
  it "should call 'bar' with appropriate arguments" do
     subject.stub(:bar)
     subject.foo
     expect(subject).to have_received(:bar).with("Invalid number of arguments")
  end
end
Run Code Online (Sandbox Code Playgroud)

文档:https://github.com/rspec/rspec-mocks#expecting-arguments