Ruby-on-rails 如何在 RSpec 中多次说“should_receive”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1328277/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 21:40:04  来源:igfitidea点击:

How to say "should_receive" more times in RSpec

ruby-on-railsrspec

提问by Jakub Arnold

I have this in my test

我的测试中有这个

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

but when object receive that method call two times, I have to do

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

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

Is there any way how to say something like

有没有办法怎么说

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

回答by Staelen

This is outdated. Please check Uri's answerbelow

这是过时的。请在下面查看Uri 的回答

for 2 times:

2次:

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

for exactly n times:

正好 n 次:

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

for at least n times:

至少 n 次:

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

more details at https://www.relishapp.com/rspec/rspec-mocks/v/2-13/docs/message-expectations/receive-countsunder Receive Counts

更多详细信息,访问https://www.relishapp.com/rspec/rspec-mocks/v/2-13/docs/message-expectations/receive-counts下的Receive Counts

Hope it helps =)

希望它有帮助 =)

回答by Uri Agassi

The new expectsyntax of rspec will look like this:

expectrspec的新语法如下所示:

for 2 times:

2次:

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

for exactly n times:

正好 n 次:

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

for at least n times:

至少 n 次:

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

回答by Prasanna

@JaredBeck pointed out. The solution didn't work for me on any_instancecall.

@JaredBeck 指出。该解决方案对我不起作用any_instance

For any instance i ended up using stub instead of should_receive.

对于任何实例,我最终使用的是存根而不是 should_receive。

Project.any_instance.stub(:some_method).and_return("value")

This will work for any no. of times though.

这将适用于任何否。虽然有时。

回答by amnsan

should_receive, as opposed to any_instance, expects that the class receives message the specified number of times.

should_receive,而不是any_instance,期望类接收消息指定的次数。

any_instanceon the other hand is generally used for stubbing a method.

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

So the first case is an expectation that we would like to test, while the second one is getting past a method to the next line so we can move on.

所以第一种情况是我们想要测试的期望,而第二种情况是通过一个方法到下一行,所以我们可以继续。