Hooks vs Background (Cucumber)

Veena Sravanthi
3 min readSep 20, 2021

We need some preconditions to run our scenario or a group of scenarios sharing the same steps repeatedly in Cucumber. We can use background or hooks to set up these conditions. How to know what is the best to use ? I was confused when I first started working on a Cucumber project.In one of my scenarios, I have wrongly added repeated steps in the background instead of using a hook. This resulted in opening multiple instances of browsers instead of one. This issue motivated me in exploring more about hooks and background. Today, I am going to share some examples with best practices surrounding usage of background and hooks.

Introduction to hooks

Cucumber supports hooks, which are blocks of code that run before or after each scenario. Cucumber hooks allows us to better manage the code workflow and helps us to reduce the code redundancy.

Types of hooks

@Before and @After tagging a method with either of these will cause the method to run before or after each scenario runs. Common functionality like starting or closing browsers are nice to place in these hooks. They reduce the number of common test steps in each scenario. Before hooks will be run before the first step of each scenario. They will run in the same order of which they are registered. After hooks will be run after the last step of each scenario, even when there are failing, undefined, pending or skipped steps.

Background

Background is used to set up a precondition.A Background is run before each scenario, but after any Before hooks. In a feature file, we should add the Background before the first Scenario.Occasionally we’ll find ourselves repeating the same Given steps in all of the scenarios in a feature. We can add such repeating Given steps to the background, by grouping them under a Background section.

Execution order of @before vs Background

In fact, as you noticed already, their structures are a little bit different. The common practice is to use them as follows:

* Use Background when you provide customer-readable preconditions to your scenarios

* Use Before when you have to do some technical setup before your scenarios

They just represent different levels of preconditions.But the main thing to understand here is the order of the operations:

Before Hook 1 -> Before Hook 2 -> … -> Background ->Scenario

Summary

References :

https://azevedorafaela.com/2016/10/08/hooks-vs-backgrounds-cucumber/

Happy Testing!!!

--

--