如何仅在第一次调用时存根方法,而在第二次调用中它应该按预期运行?
我有以下方法:
def method
do_stuff
rescue => MyException
sleep rand
retry
end
我想要的第一个电话do_stuff
募集MyException
,但在第二次调用中,行为正常。我需要实现这个来测试我的rescue
阻止而不会出现无限循环。
有办法实现这一点吗?
您可以将一个块传递给存根,该存根将在调用存根时被调用。然后,除了执行您需要执行的操作之外,您还可以在其中执行取消存根操作。
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
似乎在这里工作得很好。
$ rspec stub.rb -f doc
Stub once
should only stub once
Finished in 0.00058 seconds
1 example, 0 failures
或者,您可以只跟踪调用次数并根据调用计数返回存根的不同结果:
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)