I have the following view that requires a user to be authenticated to access it, otherwise redirects to the login page:
In my urls.py
file:
from . import views
urlpatterns = [
path("settings", login_required(views.Settings.as_view()), name="settings"),
]
In my views.py
file:
class Settings(View):
def get(self, request):
return render(request, "project/settings.html")
How can I test this view?
Here is what I tried:
class TestViews(TestCase):
def setUp(self):
self.user = User.objects.create(
username="testUser",
password="testPassword",
)
def test_settings_authenticated(self):
client = Client()
client.login(username="testUser", password="testPassword")
response = client.get("/settings")
self.assertEquals(response.status_code, 200)
self.assertTemplateUsed(response, "project/settings.html")
But this returns a 302
status, implying the user was not authenticated.
Instead of User.objects.create(...) use User.objects.create_user(...) since the create method will not automatically hash the password.
This solved my problem.