首页 > 解决方案 > 如何在 rails/rspec 中捕获 ActiveRecord::RecordInvalid 错误

问题描述

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

规格

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 错误?

标签: ruby-on-railsrubyrspec

解决方案


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

所以,使用:

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

反而


推荐阅读