Search code examples
ruby-on-railsrubyvalidationactiverecordminitest

Rails ActiveRecord validation: Assert of errors.added? :inclusion unexpectedly fails with a false negative


In my Rails (version 6.0.5.1) ActiveRecord model, I have an inclusion validation like this one:

validates :car_type, inclusion: ['coupe', 'sedan', 'convertible']

In the corresponding test file, I'm attempting to test that a validation error is raised when a value not in the list of valid values (like 'airplane') is assigned to this car_type attribute.

The following MiniTest assertions pass, as expected:

assert car.errors.invalid?
assert car.errors.include? :car_type
assert car.errors.added? :car_type, 'is not included in the list'

However, the following assertion fails with Minitest::Assertion: Expected false to be truthy.:

assert car.errors.added? :car_type, :inclusion

I would expect that this syntax should work, per this answer, and its linked ActiveRecord i18n translation file.

How can I get this last assertion to work as expected?


Solution

  • There was a change in behavior in Rails 5.2.2 where, when calling .errors.added ... :inclusion on an ActiveRecord object, a 3rd value parameter must be added specifying the invalid value.

    This assertion passes, as expected:

    assert car.errors.added? :car_type, :inclusion, value: 'airplane'
    

    Reference: https://github.com/rails/rails/issues/34652