nitin_cherian
nitin_cherian

Reputation: 6675

Writing Django signup form tests for checking new user creation

Implemented a custom user model in Django and allows user to signup using the url http://127.0.0.1:8000/users/signup/. A GET request on this url is displayed like this:

enter image description here

I have written tests for this page. Tests for get is working as expected.

I wrote test for post with the intention that the post would create a user in the test database. After which I could write tests to confirm if an user is created and whether the username matches and so on. But it seems the user is not getting created. Below are my tests

class SignUpPageTests(TestCase):
    def setUp(self) -> None:
        self.username = 'testuser'
        self.email = '[email protected]'
        self.age = 20
        self.password = 'password'

    def test_signup_page_url(self):
        response = self.client.get("/users/signup/")
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, template_name='signup.html')

    def test_signup_page_view_name(self):
        response = self.client.get(reverse('signup'))
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, template_name='signup.html')

    def test_signup_form(self):
        response = self.client.post(reverse('signup'), data={
            'username': self.username,
            'email': self.email,
            'age': self.age,
            'password1': self.password,
            'password2': self.password
        })
        self.assertEqual(response.status_code, 200)

        users = get_user_model().objects.all()
        self.assertEqual(users.count(), 1)

The users.count() turns out to be 0 and my test is failing. Where am I going wrong?

Upvotes: 5

Views: 4239

Answers (1)

Daniel Gomez Antonio
Daniel Gomez Antonio

Reputation: 41

I had the same issue and realized the problem was that the form validation was failing, you can confirm manually (running the server) that if you use password as your password then Django complains saying This password is too common. So, you need to use a different password.

Also, in my test I expected a code 302 instead of 200, because I redirect after the signup.

Upvotes: 4

Related Questions