I'd like to simulate requests to my views in Django when I'm writing tests. This is mainly to test the forms. Here's a snippet of a simple test request:
from django.tests import TestCase
class MyTests(TestCase):
def test_forms(self):
response = self.client.post("/my/form/", {'something':'something'})
self.assertEqual(response.status_code, 200) # we get our page back with an error
The page always returns a response of 200 whether there's an form error or not. How can I check that my Form failed and that the particular field (soemthing
) had an error?
https://docs.djangoproject.com/en/stable/topics/testing/tools/#django.test.SimpleTestCase.assertFormError
Where "form" is the context variable name for your form, "something" is the field name, and "This field is required." is the exact text of the expected validation error.
I think if you just want to test the form, then you should just test the form and not the view where the form is rendered. Example to get an idea:
The original 2011 answer was
But I see now (2018) there is a whole crowd of applicable asserts available:
Take your pick.