Shoulda rspec matchers :on => :create
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: ca开发者_运维知识库tegory 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?
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.
精彩评论