【发布时间】: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