Skip to content
Permalink
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
89 lines (65 sloc) 3.13 KB

Django Test Integration

There are now at least 2 projects that integrate Django and :pypi:`behave`. Both use a LiveServerTestCase to spin up a runserver for the tests automatically, and shut it down when done with the test run. The approach used for integrating Django, though, varies slightly.

:pypi:`behave-django`
Provides a dedicated management command. Easy, automatic integration (thanks to monkey patching). Behave tests are run with python manage.py behave. Allows running tests against an existing database as a special feature. See setup behave-django and usage instructions.
:pypi:`django-behave`
Provides a Django-specific TestRunner for Behave, which is set with the TEST_RUNNER property in your settings. Behave tests are run with the usual python manage.py test <app_name> by default. See setup django-behave instructions.

Manual Integration

Alternatively, you can integrate Django using the following boilerplate code in your environment.py file:

# -- FILE: my_django/behave_fixtures.py
from behave import fixture
import django
from django.test.runner import DiscoverRunner
from django.test.testcases import LiveServerTestCase

@fixture
def django_test_runner(context):
    django.setup()
    context.test_runner = DiscoverRunner()
    context.test_runner.setup_test_environment()
    context.old_db_config = context.test_runner.setup_databases()
    yield
    context.test_runner.teardown_databases(context.old_db_config)
    context.test_runner.teardown_test_environment()

@fixture
def django_test_case(context):
    context.test_case = LiveServerTestCase
    context.test_case.setUpClass()
    yield
    context.test_case.tearDownClass()
    del context.test_case
# -- FILE: features/environment.py
from behave import use_fixture
from my_django.behave_fixtures import django_test_runner, django_test_case
import os

os.environ["DJANGO_SETTINGS_MODULE"] = "test_project.settings"

def before_all(context):
    use_fixture(django_test_runner, context)

def before_scenario(context, scenario):
    use_fixture(django_test_case, context)

Taken and adapted from Andrey Zarubin's blog post "BDD. PyCharm + Python & Django".

Strategies and Tooling

See :ref:`id.practicaltips` for automation libraries and implementation tips on your BDD tests.

You can’t perform that action at this time.