rspec - how to check that allow_blank exists

不羁的心 提交于 2020-01-24 11:06:29

问题


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 methodallow_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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!