I'd like to know when testing views is it better to create a request object using RequestFactory().get() or Client().get() or calling the view directly
RequestFactory():
from django.test import RequestFactory
from django.urls import reverse
def test_profile_view(self):
p1 = mixer.blend(Profile)
path = reverse('profile', kwargs={'pk': p1.id})
request = RequestFactory().get(path)
request.user = p1.user
response2 = views.profile_view(request, pk=p1.id)
assert response.status_code == 200
assert response.streaming == False
assert response2.charset == 'utf-8'
assert response2.status_code == 200
Client():
from django.test import Client
class TestView():
def test_profile_view(self):
p1 = mixer.blend(Profile)
path = reverse('profile', kwargs={'pk': p1.id})
response= Client().get(path)
response.user = p1.user
response2 = views.profile_view(request, pk=p1.id)
assert response.status_code == 200
assert response.streaming == False
assert response2.charset == 'utf-8'
assert response2.status_code == 200
and would like to understand the difference.
If you use the RequestFactory and call the view, then you avoid the middlewares. This has the benefit that less codes gets executed and your test is faster.
But it has the drawback, that things might be a bit different on the production site, since on prod the middlewares get called.
I use Django since several years, and I am unsure again and again what is better. It makes no big difference.
BTW: This looks strange: response.user = p1.user