Randy Tang
Randy Tang

Reputation: 4353

django test the correct template used: with self.assertTemplateUsed()

I used to see the following tests in Django:

with self.assertTemplateUsed('<someTemplate>'):
    response = self.client.get('<someURL>')
    self.assertEqual(response.status_code, 200)

Question:

Since we have already had the with part, is it necessary to test the status_code? In other words, is the final statement redundant?

Upvotes: 3

Views: 1694

Answers (2)

v1k45
v1k45

Reputation: 8250

It is always a good idea to test status_code even with views rendering templates.

Django gives you ability to pass status code of your wish while rendering templates.

Both render() and render_to_response take status as keyword argument so that you can render the page with a status code you think is appropriate for the view.

Thus, you can render templates with any response status code not just 200. This gives you a reason to test status code while using assertTemplateUsed as a context manager.

Upvotes: 5

levi
levi

Reputation: 22697

It's not redundant if you app might send different responses status using the same template. In general cases, using the assertTemplateUsed it's just fine.

Upvotes: 2

Related Questions