summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorFelipe Lee <35938642+felipe-lee@users.noreply.github.com>2019-12-04 09:36:42 -0600
committerCarlton Gibson <carlton.gibson@noumenal.es>2019-12-04 16:41:46 +0100
commit87483757c80e76ea85586f2cb81bdfa1976d10e2 (patch)
tree30fe0033170340989b5db95ac0bb2aba11984e24
parent84936ac2c543007179d8fb460df1d0e6847cac61 (diff)
[3.0.x] Fixed #20456 -- Added example of directly testing CBVs in topics docs.
Backport of a2e96f7969059fb4e621a1cd591fbdd0d4deae2e from master
-rw-r--r--docs/topics/testing/advanced.txt42
1 files changed, 42 insertions, 0 deletions
diff --git a/docs/topics/testing/advanced.txt b/docs/topics/testing/advanced.txt
index 84df321d0d..cdff8889ee 100644
--- a/docs/topics/testing/advanced.txt
+++ b/docs/topics/testing/advanced.txt
@@ -67,6 +67,48 @@ The following is a unit test using the request factory::
response = MyView.as_view()(request)
self.assertEqual(response.status_code, 200)
+Testing class-based views
+=========================
+
+In order to test class-based views outside of the request/response cycle you
+must ensure that they are configured correctly, by calling
+:meth:`~django.views.generic.base.View.setup` after instantiation.
+
+For example, assuming the following class-based view:
+
+.. code-block:: python
+ :caption: views.py
+
+ from django.views.generic import TemplateView
+
+
+ class HomeView(TemplateView):
+ template_name = 'myapp/home.html'
+
+ def get_context_data(self, **kwargs):
+ kwargs['environment'] = 'Production'
+ return super().get_context_data(**kwargs)
+
+You may directly test the ``get_context_data()`` method by first instantiating
+the view, then passing a ``request`` to ``setup()``, before proceeding with
+your test's code:
+
+.. code-block:: python
+ :caption: tests.py
+
+ from django.test import RequestFactory, TestCase
+ from .views import HomeView
+
+
+ class HomePageTest(TestCase):
+ def test_environment_set_in_context(self):
+ request = RequestFactory().get('/')
+ view = HomeView()
+ view.setup(request)
+
+ context = view.get_context_data()
+ self.assertIn('environment', context)
+
.. _topics-testing-advanced-multiple-hosts:
Tests and multiple host names