Shoulda-matchers: Handling of ActiveRecord enum in validate_inclusion_of matcher

Created on 14 Aug 2018  Â·  4Comments  Â·  Source: thoughtbot/shoulda-matchers

The next portion of code:

class MyObject < ActiveRecord::Base
  enum light: { on: "on", off: "off" }
  validates :direction, inclusion: { in: lights.keys }
end


describe MyObject do
  it { should validate_inclusion_of(:light).in_array(%w(on off)) }
end

Throws this issue:

 Failure/Error: it { should validate_inclusion_of(:light).in_array(%w(on off)) }
ArgumentError:
  'shouldamatchersteststring' is not a valid light

My guess would be that the error thrown by ActiveRecord enum when string is set is not catched.

Most helpful comment

Hi @BuonOmo

There is a specific matcher for enums:

it { should define_enum_for(:light).with(%w(on off)) }

http://matchers.shoulda.io/docs/v3.1.1/Shoulda/Matchers/ActiveRecord.html#define_enum_for-instance_method

All 4 comments

The error displays validate_inclusion_of(:light) but the code is validate_inclusion_of(:direction)

Could you check if the code that you are running is checking for inclusion_on :direction or :light?

It is a typo in writing, I simplified the example. There is no typo in the original 🙂

Hi @BuonOmo

There is a specific matcher for enums:

it { should define_enum_for(:light).with(%w(on off)) }

http://matchers.shoulda.io/docs/v3.1.1/Shoulda/Matchers/ActiveRecord.html#define_enum_for-instance_method

Of course there is… Thank you!

On Aug 16, 2018, at 1:19 PM, Gui Vieira notifications@github.com wrote:

Hi @BuonOmo https://github.com/BuonOmo
The is a specific matcher for enums:

it { should define_enum_for(:light).with(%w(on off)) }

http://matchers.shoulda.io/docs/v3.1.1/Shoulda/Matchers/ActiveRecord.html#define_enum_for-instance_method http://matchers.shoulda.io/docs/v3.1.1/Shoulda/Matchers/ActiveRecord.html#define_enum_for-instance_method
—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub https://github.com/thoughtbot/shoulda-matchers/issues/1121#issuecomment-413511316, or mute the thread https://github.com/notifications/unsubscribe-auth/AK2e-AsBbqQ_kCS2r0U1xieognVrTLNMks5uRVUrgaJpZM4V8xIn.

Was this page helpful?
0 / 5 - 0 ratings