如何在 rails/rspec 中捕获 ActiveRecord::RecordInvalid 错误

How to catch an ActiveRecord::RecordInvalid error in rails/rspec

我想在 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 错误?

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

所以,使用:

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

改为

所以我想出了一个可能的解决方案,使用括号而不是括号

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

暂时不在这里发布,但我不确定这是否是最佳解决方案

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

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

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