Added AR extension error_messages_for to enable model.error_messages_for(:attribute).should for better validation testing #324

wants to merge 1 commit into


None yet
2 participants

Extension to enhance AR Model instances allowing attribute validation by checking the validation message itself, instead of the attribute's error count.

model.error_message_on(:attribute).should == 'msg'

Is equivalent to, yet more natural sounding, than what you can do today:

model.errors[:attribute].should include('msg') 

Reasoning: If there are two or more validations for :attribute, each should be tested. Simply calling model.should have(1).error_on(:attribute) could yield false positives if the wrong validation fires. It's better to check that the proper validation was triggered via the validation message

For zero errors, nil is returned (allowing a be_blank check). For one error message, the AR infused array is dropped, returning just a string, making the test should more natural (e.g. == 'msg' instead of eq(['msg']). For two or more errors, the standard string array is returned.

One could argue that this is not an rspec-rails method, and belongs instead in a active record extension library. Therefore, I'll not be offended it the pull request is denied for that (or any other reason)


Added AR extension error_messages_for to enable model.error_messages_…
…for(:attribute).should for better validation testing

dchelimsky commented Mar 5, 2011

We've already got error[s]_on, so I obviously don't have a problem w/ extending AR :)

The only thing I wonder is whether this would work better as an extension to the existing error[s]_on. Something like `model.should have(1).error_on(:attr).with("message"). Might be trickier to implement, but then it's just an extension of an existing API rather than a new one. WDYT?

I like it; it still reads well and it keeps all validation related code together tied to error_on . I'll close this Pull Request and start another.


This issue was closed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment