Index
- Introduction
1.1 Shared Steps
1.2 Hooks
- Implementation
4.1 Shared Steps Implementation
4.2 Hooks Implementation
1. Introduction
1.1 Shared Steps
Shared steps are common steps that can be used by any feature file regardless where they are located in the project hierarchy.
1.2 Hooks
Hooks are an additional logic that can be inserted anywhere during the execution of a feature file.
Whether it is before and after a scenario or before and after a step.
Types of Hooks available in pytest-bdd.

2. Conftest
The shared steps and hooks are located at the “conftest.py” file.
The “conftest.py” is located together with the tests modules that are in the “/tests” directory.

3. Initial Setup
We are going to continue from a previous automation project “Adding Tags to Gherkin Scenarios”.
Make sure you clone the right branch so we can start: “tutorial/gherkin-tags”.

After cloning it, check in the VSCode if you cloned the right branch.

4. Implementation
4.1 Shared Steps Implementation
In the project you’ve just cloned, inside the “web.feature” file it already has implemented a shared step that runs before every scenario.
“web.feature”:
Background:
Given the DuckDuckGo home page is displayed
The feature implementation is in the step definition file called “test_web_steps.py” you can see in the code snippet below.
You just have to move the code snippet below from “test_web_steps.py” to “conftest.py” where the shared steps should be located.
“test_web_steps.py” -> “conftest.py”:
# Shared given steps
from pytest_bdd import given
from pages.search import DuckDuckGoSearchPage
@given('the DuckDuckGo home page is displayed', target_fixture="duckduckgo_home")
def duckduckgo_home(browser):
DuckDuckGoSearchPage(browser).load()
pass
That’s it, now you have a shared step inside your conftest file that is accessible by the feature files.
4.2 Hooks Implementation
You can see below the example of a hook that will print a message whenever there is an execution error.
“conftest.py”:
# Hooks
import pytest
def pytest_bdd_step_error(request, feature, scenario, step, step_func, step_func_args, exception):
print(f'Step failed: {step}')
5. Running Tests
- Before running the tests, change the expected result in one of them for it to fail and you can see the hook working.
- In the example below I changed the scenario “Lengthy DuckDuckGo Search” expected result from “Declaration of Independence” to “Declaration of Happiness”.

Run the test and the hook message will be shown.
pipenv run python -m pytest

6. Repository
I created a new branch called “tutorial/sharedsteps-and-hooks” for this tutorial, click the link below to see it:
https://github.com/LuizGustavoR/intro-selenium-py/tree/tutorial/sharedsteps-and-hooks
The end.
7. Thanks
- This guide was created based on the course “Behavior Driven Python with pytest-bdd” by Andrew Knight.
- Course available at “Testing Automation University”.