RSpec 如何存根打开? [英] RSpec how to stub open?
问题描述
我一直在尝试存根 open
,open-uri 版本,但没有成功.
I've been trying to stub open
, the open-uri version, and I'm not succeeding.
我尝试执行以下操作,但请求一直通过:
I've tried doing the following but the request keeps going through:
Kernel.should_receive(:open).and_return("Whatever for now")
我也尝试过
OpenURI::OpenRead.should_receive(:open).and_return("Whatever for now")
自从我追踪到那是在 OpenURI 中发出 HTTP 请求的地方.
Since I tracked down that was where HTTP requests were made in OpenURI.
预先感谢您的任何建议!
Thanks in advance for any suggestions!
推荐答案
在谷歌上呆了一段时间后,我在 Stack Overflow 上找到了一个解决方案(我不敢相信我以前没有找到这个).
I found a solution here on Stack Overflow after some more time on Google (I can't believe I didn't find this before).
解释取自此处,由Tony Pitluga(不可链接).
Explanation taken from here and written by Tony Pitluga (not linkable).
如果你在一个对象的上下文中调用 sleep ,你应该在对象上存根它[...]
关键是,在调用 sleep 的上下文中,将 sleep 置入任何self".
If you are calling sleep within the context of an object, you should stub it on the object[...]
The key is, to stub sleep on whatever "self" is in the context where sleep is called.
所以我这样做了,一切都解决了:
So I did this and it all worked out:
let(:read) { mock('open') }
it "should return the new log-level when the log level was set successfully" do
read.stub(:read).and_return('log-level set to 1')
kannel.should_receive(:open).and_return(read)
kannel.set_log_level(1).should == 1
end
这篇关于RSpec 如何存根打开?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!