How can I test :inclusion validation in Rails using RSpec

jake picture jake · Sep 14, 2011 · Viewed 21.9k times · Source

I have the following validation in my ActiveRecord.

validates :active, :inclusion => {:in => ['Y', 'N']}

I am using the following to test my model validations.

should_not allow_value('A').for(:active)
should allow_value('Y').for(:active)
should allow_value('N').for(:active)

Is there a cleaner and more through way of testing this? I am currently using RSpec2 and shoulda matchers.

EDIT

After some looking around I only found, this probably an 'ok' way of testing this, shoulda does not provide anything for this and anyone who requires it can write their own custom matcher for it.(And probably contribute it back to the project). Some links to discussions that might be intresting:

  • Links which indicate to the above . Link 1 , Link 2

  • should_ensure_value_in_range This one comes close to what can be used, but only accepts ranges and not a list of values. Custom matcher can be based on this.

Answer

Nathan Long picture Nathan Long · Aug 6, 2012

Use shoulda_matchers

In recent versions of shoulda-matchers (at least as of v2.7.0), you can do:

expect(subject).to validate_inclusion_of(:active).in_array(%w[Y N])

This tests that the array of acceptable values in the validation exactly matches this spec.

In earlier versions, >= v1.4 , shoulda_matchers supports this syntax:

it {should ensure_inclusion_of(:active).in_array(%w[Y N]) }