应该使用 rspec 匹配器 :on =>:创造 [英] Shoulda rspec matchers :on => :create
问题描述
我正在使用一些 Shoulda rspec 匹配器来测试我的模型,其中之一是:
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)
验证没有被触发,因为它只在更新时运行,我如何在更新和创建时使用这些 shoulda 匹配器?
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?
推荐答案
我认为应该更好地处理这个问题.我遇到了这个问题,因为我只想在创建新用户时对我的用户模型运行我的唯一性验证检查.在更新时执行数据库查询是一种浪费,因为我不允许更改用户名:
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:
validates :username, :uniqueness => { :case_sensitive => false, :on => :create },
幸运的是,您可以通过明确定义主题"来解决这个问题:
Fortunately you can get around this by explicitly defining the "subject":
describe "validation of username" do
subject { User.new }
it { should validate_uniqueness_of(:username) }
end
这种方式只是在新实例上进行测试.对于您的情况,您可能只需将主题更改为已保存在数据库中的内容,并设置所有必要的字段.
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.
这篇关于应该使用 rspec 匹配器 :on =>:创造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!