0

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.

piyush
  • 1
  • 2
  • Does this help? https://github.com/thoughtbot/shoulda-matchers/issues/1433 – Schwern Jun 23 '23 at 20:44
  • 1
    I think it doesn't like your enum. Seems they [fixed it for polymorphic associations](https://github.com/thoughtbot/shoulda-matchers/pull/1523/files) but maybe not for enums. Do you need inclusion validation on an enum? Check if enums already enforce that. – Schwern Jun 23 '23 at 20:48
  • Thanks, Good point, I will check if an inclusion check is needed when an enum is used for a column. I also check the issue and PR you mentioned before but as you said it is for fixing polymorphic association – piyush Jun 24 '23 at 21:12

2 Answers2

1

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.

tyrro
  • 41
  • 3
0

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

piyush
  • 1
  • 2