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 - 在事件记录中动态查找条件

ruby-on-rails - 当列与表不匹配时,如何可逆地删除表上的remove_foreign_key?

ruby-on-rails - 使用 ActiveRecord::Relation 对象

ruby-on-rails - 如何获取数组中的下一个和上一个元素,Ruby

mysql - 从 MySQL 修复不正确的字符串编码

ruby-on-rails - RSpec let方法不生成变量

ruby - 如何找到当前运行的 Ruby 脚本的绝对路径?

arrays - 使用 Ruby 读取 YAML,意外的返回类型

ruby - Rspec:如何测试递归?

ruby-on-rails - 如何模拟对 open-uri 的调用