alexanderdavide
alexanderdavide

Reputation: 1675

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.

Upvotes: 1

Views: 218

Answers (1)

otaviko
otaviko

Reputation: 391

Taken from the rails docs for the added? method:

If the error message requires options, then it returns true with the correct options, or false with incorrect or missing options.

Therefore the options have to fully match. The necessary option for :exclusion is the value and is passed as the last parameter:

@child_entity1.errors.added?(:parent_entity, :exclusion, value: @child_entity1)

Upvotes: 2

Related Questions