I'm trying to test my success_url method and couldn't find a way to test it correctly and increase my code coverage.
#views.py
def get_success_url(self):
if self.question.type in [
Question.MULTIPLE_TYPE,
Question.SINGLE_TYPE
]:
return reverse("question")
else:
return reverse("question_answers", kwargs={"id": self.question.pk, "type": Answer.MULTIPLE})
This is what I have tried in my tests.py file.
#tests.py
from factories import QuestionFactory
def test_get_success_url(self):
self.client.force_login(user=self.user)
question = QuestionFactory(owner=self.user)
if question.type in [
Question.MULTIPLE_TYPE,
Question.SINGLE_TYPE
]:
response = self.client.get(reverse("question"))
else:
response = self.client.get(
reverse("question_answers", kwargs={"id": self.question.pk, "type": Answer.MULTIPLE})
)
self.assertEqual(response.status_code, 200)
If you want to test the get_success_url() method in a CBV, you need to call the CBV itself. So for example:
# views.py
class SuccessTestingView(FormView):
def get_success_url():
# Your that you want to test here.
Tests:
# tests.py
from factories import QuestionFactory
class SuccessfullRedirect(TestCase):
def test_successfull_redirect_1(self):
self.client.force_login(user=self.user)
response = self.client.post(path_to_cbv, criteria_that_leads_to_first_result)
self.assertRedirects(response, reverse("question"))
def test_succesfull_redirect_2(self):
self.client.force_login(user=self.user)
response = self.client.post(path_to_cbv, criteria_that_leads_to_second_result)
self.assertRedirects(response, reverse("question_answers", kwargs={"id": self.question.pk, "type": Answer.MULTIPLE}))
You need to test the view itself and not the result of the success url call so to speak. Hope that helps.