如何仅在第一次调用时存根一个方法,而在第二次调用中它应该按预期运行?
我有以下方法:
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