Ruby on Rails testing: How can I test or at the very least see a form_for's error_messages_for?
I'm working on creating a tests, and I can't figure out why the creation of a model from a form_for is failing in the test but works in real browsers. Is there a straightforward way for me to see what the problems are in the model creation?
Even better would be, is there a straightforward way for me to test the error outputs that I access via error_messages_for? In that case, I'd like to also add in tests tha开发者_如何学Ct make sure that malformed forms are outputting the correct errors.
You can access the validation errors on an object using @model.errors
. Use @model.errors.on(:field_name)
to get an array of error messages applied to a particular field. You can also use @model.errors.invalid?(:field_name)
in your tests to assert that an error was triggered for a particular field.
For example:
test "should reject invalid post" do
@p = Post.new
assert !@p.valid?
assert_equal @p.errors.on(:title), 'cannot be blank'
end
精彩评论