假设我在Model.save
操作上运行了以下验证:
def max_count
errors.add(:base, 'Cannot save more than 5 records') if self.class.active.count == 5
end
为什么我的Model.errors
对象nil
会保存?
此帖子可用作参考How to check for a database state before saving new records。
答案 0 :(得分:1)
如果你使用binding.pry,你应该先运行
object.valid? # it will load it's errors, if any
然后你可以通过
看到它的错误object.errors
首先,使用5个is_active
对象播种测试数据库,然后编写测试:
it 'has error when creating sixth object' do
obj = Model.new(name: 'Name', is_active: true)
obj.valid?
expect(obj.errors[:base]).to eq 'Cannot save more than 5 records'
end