问题
I have a test for uniqueness which works:
it { should validate_uniqueness_of(:name).case_insensitive }
however when I try to do a similar test for name it fails
it { should validate_presence_of(:name).allow_blank }
I get this error: undefined method
allow_blank'`
回答1:
According to this list, there's no method in shoulda that can be chained to validate_presence_of that would support what you want to do. Have a look at the source code of the matcher here.
However, there is another matcher you can use:
it { should allow_value("", nil).for(:name) }
Which tests if blank values can be applied to your attribute.
The full test would then be
it { should validate_presence_of(:name) }
it { should allow_value("", nil).for(:name) }
回答2:
AFAIK, there is no matcher for allow_blank
so you could use allow_value(@subject.name.blank?)
or something similar.
As a side note, I never test model validation using the validation methods themselves as you're actually testing the wrong thing. I test them using creation of the model in question, passing it valid or invalid parameters. This will test the model much more accurately and in real-world conditions.
来源:https://stackoverflow.com/questions/11413906/rspec-how-to-check-that-allow-blank-exists