【问题标题】:How to catch an ActiveRecord::RecordInvalid error in rails/rspec如何在 rails/rspec 中捕获 ActiveRecord::RecordInvalid 错误
【发布时间】:2020-02-20 00:19:38
【问题描述】:

我想在 Rspec 上捕获 ActiveRecord 错误:(我也在使用工厂)

Rspec

it "should throw an error" do
    animal = create(:animal)
    food_store = -1;
    expect(animal.update!(food_store: food_store)).to raise_error(ActiveRecord::RecordInvalid)

验证器:

class AnimalValidator < ActiveModel::Validator
  def validate(record)
    if record.food_store < 1
      record.errors[:food_store] << "store can't be negative"
    end
  end
end

我不断收到此错误消息:

 Failure/Error: expect(animal.update!(food_store: new_share)).raise_error(ActiveRecord::RecordInvalid)

 ActiveRecord::RecordInvalid:
   Validation failed: store can't be negative

我应该如何捕捉这个 activeRecord 错误?

【问题讨论】:

  • 与您的问题无关,但您的错误消息“store can't be negative”并不完全准确,因为0 也是无效值。此外,无需在错误消息中引用store,因为该消息位于:food_store 键上。现在你的错误信息看起来像:“food store store can't be negative”。最后,已经有一个内置的验证器:validates_numericality_of :food_store, greater_than_or_equal_to: 1

标签: ruby-on-rails ruby rspec


【解决方案1】:

使用raise_error,您需要expect 一个块。如果没有块,它将执行animal.update! 代码并尝试将该方法调用的返回值作为参数传递给expect 方法,但它不能,因为它已经出错了。对于一个块,它会推迟块的执行,直到 expect 告诉它运行(即,使用 yield 或类似的),它给 RSpec 一个拦截异常的机会。

所以,使用:

expect { animal.update!(food_store: food_store) }.to raise_error(ActiveRecord::RecordInvalid)

改为

【讨论】:

  • 这是故意忽略问题的给定用例可能会更好地使用predicate matcher 进行测试,(expect(animal).not_to be_valid 并且当前读起来更像是您正在测试内置的 Rails 代码(即@ 987654331@ 如果无效则引发异常)而不是测试您的代码(如果该动物有负数,则该动物无效)
  • 或者,使用allow_value匹配器:expect(animal).to_not allow_value(-1).for(:food_store)
【解决方案2】:

所以我想出了一个潜在的解决方案,用括号代替括号

    expect {animal.update!(food_store: food_store)}.to raise_error

在这里发布它,但我不确定这是否是最好的解决方案

【讨论】:

  • 预期会引发特定错误类型通常是个好主意。否则,块内可能还有另一个错误(如 ArgumentError),您的测试将是误报,因为您正在测试 ActiveRecord::RecordInvalid 错误。测试仍会通过,但您的代码未按预期运行。
【解决方案3】:

如果您想更具体地了解引发的异常,您可以与确切的错误消息进行比较,

expect { animal.update!(food_store: food_store) }.to raise_error("Validation failed: store can't be negative")

通过这种方式,您可以验证您期望的确切验证是否失败,而不是其他任何验证。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-04
    相关资源
    最近更新 更多