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:
If you have more elements to test than a boolean Y/N then you could also try.
You can also replace the
%w()
with a constant you have defined in your model so that it tests that only the constant values are allowed.Then the test:
I found one custom shoulda matcher (in one of the projects I was working on) which attempts to coming close to test something like this:
Examples:
The matcher tries to ensure that there is a DB constraint which blows up when it tries to save it.I will attempt to give the essence of the idea. The matches? implementation does something like:
I guess if we slightly change the above to say
@subject.save
and let Rails validation blow up, we can return false when the exception string contains something which close matches the real exception error message.I know this is far from perfect to contributed back to the project, but I guess might not be a bad idea to add into your project as a custom matcher if you really want to test a lot of the
:inclusion
validation.Use shoulda_matchers
In recent versions of
shoulda-matchers
(at least as of v2.7.0), you can do: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: