eugenekgn
eugenekgn

Reputation: 1722

Check object's errors on model.save

Let's say I have the following validation run on Model.save action:

  def max_count
    errors.add(:base, 'Cannot save more than 5 records') if self.class.active.count == 5
  end

Why is my Model.errors object nil upon save?

This post can be used as a reference How to check for a database state before saving new records .

Upvotes: 2

Views: 2053

Answers (1)

Andrey Deineko
Andrey Deineko

Reputation: 52357

If you use binding.pry you should first run

object.valid? # it will load it's errors, if any

and then you can see it's errors with

object.errors

Firstly, seed the test database with 5 is_active objects, then write the test:

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

Upvotes: 3

Related Questions