ruby-on-rails - RSpec 重试抛出异常然后返回值

标签 ruby-on-rails ruby rspec

我有一个重试 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/

相关文章:

ruby-on-rails - `spring rspec` 只显示 Spring 帮助..为什么?

ruby-on-rails - 使用 omniauth 时设计跳过确认

javascript - 如何在 JavaScript 中访问 Rails View 变量?

android - NoMethodError(未定义方法 `permit!' 为 "":String):

ruby-on-rails - 关系 belongs_to 上的 activerecord where 子句

ruby-on-rails - 填充隐藏字段时出现 capybara 错误

ruby-on-rails - 使用 Ruby on Rails 的动态下拉列表 (select_tag)

ruby-on-rails - Rails - 查询时移

javascript - Jquery 绑定(bind)事件不响应

ruby-on-rails - 在大型 Rails 应用程序中加速 RSpec 测试