Should Rails controllers be tested for validations?

Clash Royale CLAN TAG#URR8PPP
Should Rails controllers be tested for validations?
I have a question about what parts of a controller should be tested in a Ruby on Rails application. Any help would be greatly appreciated.
When I create new models that need validations such as validates :name, presence: true, I always write tests for these models. For example (if the model name is User):
validates :name, presence: true
test "name should be present" do
assert_not User.new( name: nil ).valid?
end
However, I also have a controller that "goes with" the model (e.g Users). Should I also test that the controller validates its parameters even though I am already testing the model?
Example:
test "invalid user should not be created" do
assert_no_difference "User.count" do
post random_models_path, store: name: " "
end
end
I definitely am still going to test that a valid store is created, but should I check that an invalid store is not created?
Thanks
Would it be a good idea to just test the controller for only one of the possible invalid case, because if that one succeeds then I know that the model validations are probably working?
it is_expected.to validate_presence_of :name
Can I do the same thing (
it is_expected.to validate_presence_of :name ) in minitest instead of rspec?– Jacob Lockard
Aug 9 at 19:48
it is_expected.to validate_presence_of :name
You probably can, but I have no idea how. :)
– Sergio Tulentsev
Aug 9 at 19:48
1 Answer
1
Would it be a good idea to just test the controller for only one of the possible invalid case, because if that one succeeds then I know that the model validations are probably working?
That's the right idea, and is generally what I do. There's no need to test every possible combination of validation states in the controller, but it's a good idea to test two general conditions:
1) For a valid model do we save it and redirect to where we should? (Or do we render the right thing in response?)
2) For an invalid model (for any of the possible reasons it could be invalid), do we re-render the form in such a way that the user can correct the error.
This is perfect. Thanks so much!
– Jacob Lockard
Aug 10 at 0:25
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Personally, I don't see the point in testing effects of validations even in models. Most I do is verify that the validations are there.
it is_expected.to validate_presence_of :name. Why spend the effort to repeat the activerecord's tests?– Sergio Tulentsev
Aug 9 at 19:43