我有一个重试 block
def my_method
app_instances = []
attempts = 0
begin
app_instances = fetch_and_rescan_app_instances(page_n, policy_id, policy_cpath)
rescue Exception
attempts += 1
retry unless attempts > 2
raise Exception
end
page_n += 1
end
其中 fetch_and_rescan_app_instances
访问网络,因此可以抛出异常。
我想编写一个 rspec 测试,它第一次抛出异常,第二次调用时不抛出异常,所以我可以测试它是否第二次不抛出异常,my_method 不会'不要抛出异常。
我知道我可以执行 stub(:fetch_and_rescan_app_instances).and_return(1,3)
并且第一次返回 1 第二次返回 3,但我不知道如何抛出异常第一次返回一些东西。
最佳答案
您可以在 block 中计算返回值:
describe "my_method" do
before do
my_instance = ...
@times_called = 0
my_instance.stub(:fetch_and_rescan_app_instances).and_return do
@times_called += 1
raise Exception if @times_called == 1
end
end
it "raises exception first time method is called" do
my_instance.my_method().should raise_exception
end
it "does not raise an exception the second time method is called" do
begin
my_instance.my_method()
rescue Exception
end
my_instance.my_method().should_not raise_exception
end
end
请注意,您真的不应该从 Exception
中拯救出来,使用更具体的东西。请参阅:Why is it a bad style to `rescue Exception => e` in Ruby?
关于ruby-on-rails - RSpec 重试抛出异常然后返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14206477/