Rspec / shoulda: testing, that a custom validator is called

烈酒焚心 提交于 2019-12-02 06:14:27

问题


I have a custom validator (located in app/validators/uri_validator.rb) which is used in:

validates :link, uri: true

How do I specify this in my specs?

Ideally I would like to have a one-line call, such as:

it { should validate_uri_of(:link) }

How do I do this?


回答1:


Another option is to use the allow_value matcher, although not ideal it can work in some circumstances.

it { should allow_value(value_which_is_valid).for(:link) }
it { should_not allow_value(value_which_is_invalid).for(:link) }



回答2:


Use factory girl to build a model object with invalid data and one with valid data and call the be_valid matcher.

#factory girl
build(:model, link: valid_uri).should be_valid
build(:model, link: invalid_uri).should_not be_valid


来源:https://stackoverflow.com/questions/10994373/rspec-shoulda-testing-that-a-custom-validator-is-called

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