Ответ 1
Вы можете передать блок в заглушку, которая будет вызываться при вызове заглушки. Затем вы можете выполнить там незастроенный блок, в дополнение к тому, что вам нужно.
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