validation_inclusion_of rspec test case is returning ArgumentError

162 Views Asked by At

Let's consider a class with definition as shared below:

# a_type :string
class Foo < ActiveRecord::Base
    enum a_type: { fir: 'first', sec: 'second' }
    validates :a_type, presence: true, inclusion: { in: a_types.keys }
end

Rspec:

describe 'Validations' do
    it { is_expected.to validate_presence_of(:a_type) }
    it { is_expected.to validate_inclusion_of(:a_type).in_array(Foo.a_types.keys) }
end

Failure/Error: it { is_expected.to validate_inclusion_of(:a_type).in_array(Foo.a_types.keys) }

ArgumentError: 'shoulda-matchers test string' is not a valid a_type

Is this the expected behavior for this? Please help

I did try to explore ValidateInclusionOfMatcher from shoulda-matcher repo but couldn't find anything concrete.

It is not very clear why would validate inclusion fail and how does it check based on subject first and then apply ARBITRARY_OUTSIDE_STRING which results in above error.

My understanding is that it should check above behavior, one with value passed in subject using factorybot and other by replacing a_type to some random value.

2

There are 2 best solutions below

1
On

Could you try changing the column name to something else? The name type is reserved for STI, or if you want to keep it, try overwriting the inheritance column:

self.inheritance_column = nil

That being said, shoulda-matchers error message is really confusing.

0
On

There is no need to validate or explicitly check for inclusion as an enum defined for a column does that implicitly.

Thanks @Schwern for pointing it out