ruby - 防止错误导致RSpec测试失败

标签 ruby rspec error-handling

假设我有一个带有此类方法的类:

class MyClass
  ...

  def self.some_class_method
    my_instance = MyClass.new
    self.other_class_method(my_instance)
    raise 'ERROR'
  end

  def self.other_class_method(instance)
    ...
  end
end

并对其进行测试,如下所示:
require 'spec_helper'

describe MyClass do
  describe '.some_class_method' do
    context 'testing some_class_method' do
      it 'calls other_class_method' do
        MyClass.should_receive(:other_class_method)

        MyClass.some_class_method
      end
    end
  end
end

测试通过ERROR出错,并且如果我删除了raise 'ERROR'行,则测试通过。但是在这里我只想测试some_class_method是否调用other_class_method,而不管以后发生什么。我可以更改它以期望该方法会引发错误,但这不是此特定测试的目的。有没有更好的办法?

最佳答案

您可以在测试中挽救异常。

describe MyClass do
  describe '.some_class_method' do
    context 'testing some_class_method' do
      it 'calls other_class_method' do
        MyClass.should_receive(:other_class_method)
        begin
          MyClass.some_class_method
        rescue
        end
      end
    end
  end
end

关于ruby - 防止错误导致RSpec测试失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45470415/

相关文章:

ruby-on-rails - 用于生产的 Ruby 版本

Ruby:仅在某些情况下重载运算符行为

ruby - 如何分配表达式中的元素?

ruby-on-rails - 将 header 附加到 Rspec Controller 测试

ruby-on-rails - oauth 提供程序的 Rspec 测试

ruby - 在 Go 中建模 "superclass method implementation"的最佳方法是什么?

ruby-on-rails - 使用 rspec-rails 2.0.0.beta.8 模拟 View 助手

python - 初学者错误处理返回 bool 值

asp.net - 避免在我的Telerik控件中尝试/捕获 hell

error-handling - 如何在 sapper (svelte) 中捕获服务器错误