views:

24

answers:

1

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 that make sure that malformed forms are outputting the correct errors.

+1  A: 

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 [email protected]?
  assert_equal @p.errors.on(:title), 'cannot be blank'
end
Jimmy Cuadra