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

时间:2021-12-03 23:26:23

When writing RSpec tests, I find myself writing a lot of code that looks like this in order to ensure that a method was called during the execution of a test (for the sake of argument, let's just say I can't really interrogate the state of the object after the call because the operation the method performs is not easy to see the effect of).

编写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

What I want to know is: Is there a nicer syntax available than this? Am I missing some funky RSpec awesomeness that would reduce the above code down to a few lines? should_receive sounds like it should do this but reading further it sounds like that's not exactly what it does.

我想知道的是:有比这个更好的语法吗?我是否漏掉了一些古怪的RSpec,可以将上面的代码减少到几行?should_receive听起来应该这么做,但是读得更深听起来它并不是这样做的。

3 个解决方案

#1


105  

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

#2


91  

In the new rspec expect syntax this would be:

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

expect(subject).to receive(:bar).with("an argument I want")

#3


28  

The below should work

下面的工作

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

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

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

#1


105  

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

#2


91  

In the new rspec expect syntax this would be:

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

expect(subject).to receive(:bar).with("an argument I want")

#3


28  

The below should work

下面的工作

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

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

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