Test Flask render_template() context

flask, jinja2, python

Solution

You can use the `assert_template_used` method of `TestCase` provided by flask-testing.

from flask.ext.testing import TestCase

class MyTest(TestCase):

    def create_app(self):
        return myflaskapp

    def test_greeting(self):
        self.app.get('/')
        self.assert_template_used('hello.html')
        self.assert_context("greeting", "hello")

The method `create_app` must provide your flask app.

Problem

I have a Flask route that looks like this: ``` @app.route('/') def home(): return render_template( 'home.html', greeting:"hello" ) ``` How do I test that the `'home.html'` template was rendered, and that the `render_template()` context defined the `greeting` variable with a particular value? These should be (and probably are) pretty easy to test, but I'm really not sure how to do this with Flask and unittest.

Original source