Reputation: 682
I am working on testing - and I have a little form with a good chunk of logic in the clean method.
My test looks like this:
class DependentFormTest(TestCase):
def test_dependent_form_birthdate_out_of_range(self):
form_data = {
'first_name': 'Bill',
'last_name': 'Robusin',
'birth_date': '10/12/1801',
'gender': 'Male',
'relationship': 'dependent',
'street_address_1': '123 Any lane',
'city': 'Billson',
'state': 'WA',
'zip': '50133',
}
form = DependentForm(data=form_data)
self.assertFalse(form.is_valid())
In my clean method there is a bit where I access some information about the current user. The snippet that fails looks like this:
user_benefit = Benefit.objects.get(user=self.user)
This line is what causes my test to error with the following error:
Benefit matching query does not exist
This is true, because in the test 'user' is 'None'.
How do I set a user in my test so that I can test this forms validity?
Upvotes: 0
Views: 574
Reputation: 611
You can't access the user in a form's clean
method if the user is not set explicitly during the forms initialization (see here: django: how to access current request user in ModelForm? )
If you pass the user to the constructor during form initialization, you can also do that in your test.
user = User.objects.first() # probably you should think about a better way to obtain a user instance
form = DependentForm(data=form_data, user=user)
self.assertFalse(form.is_valid())
Upvotes: 1
Reputation:
in your test setUp()
method you could create a user for testing purposes. and then reuse it.
As far as i understand your user comes from the request. So you would need to use django test client to login and post the data into your form.
Upvotes: 2