fot*_*nus 19 ruby rspec stubbing
如何仅在第一次调用时存根方法,在第二次调用中它应该按预期运行?
我有以下方法:
def method
do_stuff
rescue => MyException
sleep rand
retry
end
Run Code Online (Sandbox Code Playgroud)
我想的第一个电话do_stuff,以提高MyException,但在第二个电话,可以正常工作.我需要实现这个来测试我的rescue块而不会得到无限循环.
有没有办法实现这个目标?
Chr*_*ald 17
您可以将块传递给将在调用存根时调用的存根.然后你可以在那里执行unstub,除了做你需要的任何事情.
class Foo
def initialize
@calls = 0
end
def be_persistent
begin
increment
rescue
retry
end
end
def increment
@calls += 1
end
end
describe "Stub once" do
let(:f) { Foo.new }
before {
f.stub(:increment) { f.unstub(:increment); raise "boom" }
}
it "should only stub once" do
f.be_persistent.should == 1
end
end
Run Code Online (Sandbox Code Playgroud)
好像在这里工作得很好.
$ rspec stub.rb -f doc
Stub once
should only stub once
Finished in 0.00058 seconds
1 example, 0 failures
Run Code Online (Sandbox Code Playgroud)
或者,您可以跟踪调用次数,并根据调用次数返回存根的不同结果:
describe "Stub once" do
let(:f) { Foo.new }
it "should return different things when re-called" do
call_count = 0
f.should_receive(:increment).twice {
if (call_count += 1) == 1
raise "boom"
else
"success!"
end
}
f.be_persistent.should == "success!"
end
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6098 次 |
| 最近记录: |