如何在RSpec中多次说“ should_receive”


112

我测试中有这个

Project.should_receive(:find).with(@project).and_return(@project)

但是当对象两次收到该方法调用时,我必须做

Project.should_receive(:find).with(@project).and_return(@project)
Project.should_receive(:find).with(@project).and_return(@project)

有什么办法怎么说

Project.should_receive(:find).with(@project).and_return(@project).times(2)

Answers:


214

这已经过时了。请在下面查看Uri的答案

2次:

Project.should_receive(:find).twice.with(@project).and_return(@project)

恰好n次:

Project.should_receive(:find).exactly(n).times.with(@project).and_return(@project)

至少n次:

Project.should_receive(:msg).at_least(n).times.with(@project).and_return(@project)

有关更多详细信息,参见https://www.relishapp.com/rspec/rspec-mocks/v/2-13/docs/message-expectations/receive-counts下的“ 接收计数”

希望对您有帮助=)


3
似乎这可能不起作用any_instance
杰瑞德·贝克

@YoLudke我不知道
Jared

2
应该使用Uri的答案中提到的新语法。
theblang '16

61

expectrspec 的新语法如下所示:

2次:

expect(Project).to receive(:find).twice.with(@project).and_return(@project)

恰好n次:

expect(Project).to receive(:find).exactly(n).times.with(@project).and_return(@project)

至少n次:

expect(Project).to receive(:msg).at_least(n).times.with(@project).and_return(@project)

1
have_received语法也适用。expect(Project).to have_received(:find).exactly(n).times
David Tuite 2014年


0

should_receive与相对any_instance,期望类接收指定次数的消息。

any_instance 另一方面,通常用于存根方法。

因此,第一种情况是我们要测试的期望,而第二种情况是将方法传递到下一行,因此我们可以继续进行。


1
Drenmi,我很感谢您花时间在我将近一年前添加的帖子中添加几个逗号。看起来好像答案的技术方面没有任何变化。您为什么拒绝投票?我为此...?
2015年
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.