Search code examples
djangodjango-tests

Django test for a page that redirects


I am trying to write a test for a View that redirects to the dashboard but I'm not getting something right. A user must be authenticated before he/she can access the (membership) View. In my urls.py, I have something like

...
path('membership/', MembershipView.as_view(), name='membership'),
...

Then my tests.py contains

class TestApp(TestCase):
    def test_that_membership_resolves(self):
        client = Client()
        response = client.post('/membership/', {
            # I then pass the necessary values in a dictionary
            ...
            ...
        })
        self.assertRedirects(response, reverse("src:dashboard"))

But the I am getting an error which says

self.assertEqual(
AssertionError: '/login/?next=%2Fmembership%2F' != '/dashboard'
- /login/?next=%2Fmembership%2F
+ /dashboard
 : Response redirected to '/login/?next=/membership/', expected '/dashboard'Expected '/login/?next=/membership/' to equal '/dashboard'.

I think it's telling me to login first. I already have a test a method that tests for login and the test passes. How can I solve this issue here?


Solution

  • Then just login first after instancing your client. Your view only works by logging in, so you need to login first?

    client.login(email="[email protected]", password="testpass123")
    

    Or whatever user login works in your test setUp

    Edit: use a setUp for all your tests, so you have some initial data for all of them:

    class TestViews(TestCase):
        def setUp(self):
            self.user = get_user_model().objects.create_user(email="[email protected]",password="testpass123",)
        def test_that_membership_resolves(self):
            client = Client()
            client.login(email="[email protected]", password="testpass123")
            response = client.post('/membership/', {
                # I then pass the necessary values in a dictionary
                ...
                ...
            })
            self.assertRedirects(response, reverse("src:dashboard"))
    
    
        def test_whatever_else_comes_next_to_test(self):
            # use your setUp data again for another test