Skip to content

Instantly share code, notes, and snippets.

Created June 9, 2014 00:13
Show Gist options
  • Save anonymous/479d287507c28c20a53a to your computer and use it in GitHub Desktop.
Save anonymous/479d287507c28c20a53a to your computer and use it in GitHub Desktop.

Here's a view using TemplateResponse. This test will run without needing to set up urls or add templates to the file system.

def my_view(request, template_name):
     return TemplateResponse(request, template_name, {"foo": "bar"})


class MyTest(TestCase):

     def test_get(self):
         request = RequestFactory().get("/")
         response = my_view(request, "template.html")
         self.assertEqual(response.status_code, 200)
         self.assertEqual(response.context_data["foo"], "bar")

If I use render, the template render is called, so I have to override the template loaders:

from django.test.utils import (
    setup_test_template_loader,
    restore_template_loaders,
)

def my_view(request, template_name):
     return render(request, template_name, {"foo": "bar"})

class MyTest(TestCase):

     def setUp(self):
         templates = {
             "template.html": "{{ foo }}",
         }
         setup_test_template_loader(templates)
    
     def tearDown(self):
         restore_template_loaders()

     def test_get(self):
         request = RequestFactory().get("/")
         response = my_view(request, "template.html")
         # no access to context data on response
         # self.assertEqual(response.status_code, 200)
         self.assertEqual(response.content, "bar")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment