vendredi 3 avril 2020

errors.added? returns false when used with :exclusion

In a recursive rails model I have a validation that the model cannot reference itself:

validates :parent_entity, exclusion: { in: ->(entity) { [entity] } }

This is successful and the exclusion error with the correct message is set. I can approve this via rails console.

In a Rspec test I want to check if the appropriate exclusion error is added:

it 'parent_entity cannot be same entity as child_entity' do
  @child_entity1.parent_entity = @child_entity1
  @child_entity1.valid?
  expect(@child_entity1.errors.added?(:parent_entity, :exclusion)).to be_truthy
end

The test fails returning a falsey value in the expect.

The preceding approach works flawlessly for e. g. blank errors but not with exclusion. If I exchange ':exclusion' in the test with the resolved error message 'is reserved', I can get it working but this is not what I want and should do.

Aucun commentaire:

Enregistrer un commentaire