I know, in behave, it is possible to use an environment.py
to specify before_feature()
and after_feature()
functions to execute setup and teardown code before or after every feature.
However, is there a way to specify a custom after feature function that is only executed for the specific feature?
In my searching online, I found a few pages discussing possible ways to do this using cucumber-jvm, but nothing on doing this with behave:
To give an example, I'd like to do something similar to this:
Feature: My feature
AfterFeature:
Then Database is reset
# Scenarios
One thing I thought of is maybe the context
can be looked at in the "global" after_feature()
function, and then custom code can be run if the feature's name matches the desired name. For example, something like:
# In environment.py
def after_all(context):
if context.feature.name == 'feature_with_custom_teardown.feature':
# Do custom teardown
# Do regular teardown
However, when I tried inspecting the context
in my after_all()
function, for some reason the feature was None
- but maybe this just means I was doing something wrong.
There are several ways you could do this:
In environment.py
you might add something like:
def after_feature(context, feature):
if feature.name == 'My feature':
# Do custom teardown
You could also work with feature tags instead of name, which is more practical if you know there will be more than one feature requiring the setup/teardown. So if your feature file is tagged something like
@database-reset-required
Feature: My feature
# Scenarios here
, then, for the teardown part, in environment.py
you could have:
def after_feature(context, feature):
if 'database-reset-required' in feature.tags:
# Do custom teardown
If you go for the feature.name
approach and not feature.tags
note that you need to use the *name* defined within the feature file i.e. this part Feature: *My feature*
, NOT the filename.