简体   繁体   中英

rspec - how to check that allow_blank exists

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'`

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) }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM