ruby-on-rails - 如何在 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 错误?
解决方案
有了raise_error
,你需要expect
一个块。如果没有块,它将执行animal.update!
代码并尝试将该方法调用的返回值expect
作为参数传递给该方法,但它不能,因为它已经出错了。对于一个块,它会推迟块的执行,直到它expect
告诉它运行(即,withyield
或类似的),它给 RSpec 一个拦截异常的机会。
所以,使用:
expect { animal.update!(food_store: food_store) }.to raise_error(ActiveRecord::RecordInvalid)
反而
推荐阅读
- java - 有没有办法使用 ESC 命令获取热敏打印机的状态?
- javascript - 如何使用jQuery选择树中的最后一个孩子?
- javascript - Hiding DataTable div
- r - Filling the gap in the time series
- google-analytics - How to implement the Google Analytics event monitoring on a website if the standard Analytics tracking code seems not to be enough?
- android - 限制 IPackageInstallObserver 和 IPackageDeleteObserver 上的目标 API 28
- php - 无法为移动和网络平台设置操作
- android - 在 RecyclerView 适配器中使用 Glide 加载的 Gif 无法正常播放
- mysql - 我可以获得有关如何使用以下标签加入我的表的帮助吗?
- html - 它是 Chrome 中 em DIV 的秘密最小尺寸(宽度/高度)吗?