275π
β
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:
from django.test import TestCase
from myapp.forms import MyForm
class MyTests(TestCase):
def test_forms(self):
form_data = {'something': 'something'}
form = MyForm(data=form_data)
self.assertTrue(form.is_valid())
... # other tests relating forms, for example checking the form data
87π
from django.tests import TestCase
class MyTests(TestCase):
def test_forms(self):
response = self.client.post("/my/form/", {'something':'something'})
self.assertFormError(response, 'form', 'something', 'This field is required.')
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.
π€Shane
- [Django]-How can I see the raw SQL queries Django is running?
- [Django]-Django self-referential foreign key
- [Django]-Gunicorn autoreload on source change
19π
The original 2011 answer was
self.assertContains(response, "Invalid message here", 1, 200)
But I see now (2018) there is a whole crowd of applicable asserts available:
- assertRaisesMessage
- assertFieldOutput
- assertFormError
- assertFormsetError
Take your pick.
π€John Mee
- [Django]-How do I reference a Django settings variable in my models.py?
- [Django]-Unittest Django: Mock external API, what is proper way?
- [Django]-What is actually assertEquals in Python?
Source:stackexchange.com