ruby-on-rails - Rspec raise_error 不适用于自定义错误

标签 ruby-on-rails rspec

我有一个自定义错误类 ApiError :

class ApiError < StandardError
  attr_reader :message, :code, :details, :raw_json
  def initialize(json)
    @message  = json["message"]
    @code     = json["code"]
    @raw_json = json

    super json.to_s
  end
end

所以我试着写了几个规范来测试它,但没有一个通过。
第一:
it 'raises an error' do
  expect { raise ApiError, "Some error"}.to raise_error ApiError.new("Some error")
end

它失败了:
Failure/Error: expect { raise ApiError, "Some error"}.to raise_error ApiError, "Some error"

       expected ApiError with "Some error", got #<ApiError: Some error> with backtrace:
         # ./spec/models/...:39:in `block (4 levels) in <top (required)>'
         # ./spec/models/...:39:in `block (3 levels) in <top (required)>'

还有一个让我很惊讶的选择:
it 'raises an error 2' do
  expect { raise ApiError, "Some error"}.to raise_error ApiError, "Some error"
end

它失败了:
Failure/Error: expect { raise ApiError, "Some error"}.to raise_error ApiError.new("Some error")

       expected #<ApiError: Some error>, got #<ApiError: Some error> with backtrace:
         # ./spec/models/...:43:in `block (4 levels) in <top (required)>'
         # ./spec/models...:43:in `block (3 levels) in <top (required)>'

所以呢?在消息中,它们看起来相当平等。任何人都可以知道是什么问题吗?还有,写 ApiError, "123" 有什么区别?和 ApiError.new("123")在规范文件中?

==========更新==========

用设置 message 注释掉一个字符串ApiError 类中的属性,以防它不覆盖默认值没有帮助
class ApiError < StandardError
  attr_reader :message, :code, :details, :raw_json
  def initialize(json)
    # @message  = json["message"]
    @code     = json["code"]
    @raw_json = json

    super json.to_s
  end
end

最佳答案

messageStandardError 的一个属性.您正在覆盖它和 messagenil在您的异常对象中。重命名您的属性,它应该通过

class ApiError < StandardError
  attr_reader :api_error_message, :code, :details, :raw_json
  def initialize(json)
    @api_error_message  = json["message"]
    @code     = json["code"]
    @raw_json = json

    super json.to_s
  end
end

it 'raises an error' do
  expect { raise ApiError, "Some error"}.to raise_error ApiError, "Some error"
end

更新:

如果需要设置messagejson["message"]
  class ApiError < StandardError
    attr_reader :code, :details, :raw_json
    def initialize(json)
      @code     = json["code"]
      @raw_json = json

      super json["message"]
    end
  end

  it 'raises an error' do
    expect { raise ApiError, {"message" => "Some error"}}.to raise_error(ApiError, "Some error")
  end

关于ruby-on-rails - Rspec raise_error 不适用于自定义错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45041469/

相关文章:

ruby-on-rails - Rspec/capybara - 测试一个类或另一个类的存在

ruby-on-rails - Rspec期望更改计数不起作用

ruby-on-rails - 如何使用 rspec 和 Ruby 测试父类(super class)方法抛出异常

ruby-on-rails - Mongoid - 具有引用数组的字段

ruby-on-rails - 在 Rails 中使用带有 Postgres HSTORE 的商店

ruby-on-rails - 从 Rails 导出 CSV 数据

javascript - Capybara 重定向到 JSON 响应

mysql - 使用 mysql 和 rails 3 从 2 个表返回记录

css - 如何将样式表应用于查看页面

Ruby 条件测试