stub方法仅在第一次使用Rspec调用时

如何仅在第一次调用时存根方法,在第二次调用中它应按预期运行?

我有以下方法:

def method do_stuff rescue => MyException sleep rand retry end 

我想第一次调用do_stuff来引发MyException ,但在第二次调用中,行为正常。 我需要实现这个来测试我的rescue块而不会得到无限循环。

有没有办法实现这个目标?

您可以将块传递给将在调用存根时调用的存根。 然后你可以在那里执行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 

好像在这里工作得很好。

 $ 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