In Django, I have a view, which will redirect to the register page for certain users and I would like to write a test for this.
The standard request.client.get
used for testing doesn't allow me to specify a user (it just defaults to anonymous_user
?), so I can't test the behaviour.
With RequestFactory()
I was able to specify request.user
. However, it is not following the redirect and the test fails.
from .views import my_view
from django.test import RequestFactory()
def test_mytest(self):
user = create_guest_user()
self.factory = RequestFactory()
request = self.factory.get(reverse('my_view'), follow=True)
request.user = user
response = my_view(request)
self.assertContains(response, "page where redirected should contain this")
It fails on the last line with this error message:
AssertionError: 302 != 200 : Couldn't retrieve content: Response code was 302 (expected 200)
Any ideas how to do this?
EDIT: As far as I can tell this is not a duplicate as it refers to RequestFactory()
, which is different from self.client.get
(where follow=True
will solve the problem).