应该 rspec 匹配器 :on => :创造
我正在使用一些 Shoulda rspec 匹配器来测试我的模型,其中之一是:
describe Issue do
it { should_not allow_value("test").for(:priority) }
end
我的问题是我的模型中的验证看起来像这样:
validates_format_of :priority, :with => /^(Low|Normal|High|Urgent)$/, :on => :update
因此,当运行此测试时,我得到:
1) 'Issue should not allow priority to be set to "test"' FAILED
Expected errors when priority is set to "test", got errors: category is invalid (nil)title can't be blank (nil)profile_id can't be blank (nil)
验证没有被触发因为它只在更新时运行,所以我如何在更新和创建时使用这些 shoulda 匹配器?
I am using some of the Shoulda rspec matchers to the test my model, one of them being:
describe Issue do
it { should_not allow_value("test").for(:priority) }
end
My problem with this is that my validation in my model looks like this:
validates_format_of :priority, :with => /^(Low|Normal|High|Urgent)$/, :on => :update
So when running this test I get:
1) 'Issue should not allow priority to be set to "test"' FAILED
Expected errors when priority is set to "test", got errors: category is invalid (nil)title can't be blank (nil)profile_id can't be blank (nil)
The validation isn't being triggered because it only runs on an update, how can I use these shoulda matchers on an update vs. a create?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为应该更好地处理这个问题。我遇到这个问题是因为我只想在创建新用户时对我的用户模型运行唯一性验证检查。在更新时执行此操作是浪费数据库查询,因为我不允许更改用户名:
幸运的是,您可以通过显式定义“主题”来解决此问题:
这样它仅在新实例上进行测试。对于您的情况,您可能只需将主题更改为已保存在数据库中的内容,并设置所有必要的字段。
I think shoulda should handle this better. I ran into this because I only want to run my uniqueness validation check for my User model when creating new users. It's a waste of a database query doing it on update, since I don't allow usernames to be changed:
Fortunately you can get around this by explicitly defining the "subject":
This way it's only testing on a new instance. For your case, you can probably just change the subject to be something saved in the database already, with all the necessary fields set.