0

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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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())

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.