检查model.save上的对象错误

时间:2016-01-24 17:00:27

标签: ruby-on-rails ruby ruby-on-rails-4

假设我在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

1 个答案:

答案 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