Cucumber | @Before hook Vs Background | Usage
2 min readMar 15, 2019
Assumption here — we have good understanding of following tool / terminologies.
- Cucumber tool (Basic Idea)
- BDD (Behavior Driven Development)
- Gherkin Syntax / Feature File
What are Hooks and “@Before” hook?
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.
- We can say that it is an unseen step, which allows us to perform our scenarios or tests.
- They are typically used for setup and tear down of the environment before and after each scenario.
- @Before and @After tagging a method with either of these will cause the method to run before or after each scenario runs. They will run in the same order of which they are registered.
- Common functionality like starting or stop browsers are nice to place in these hooks.
What is Background?
- Use Background only to setup a pre-condition that the user needs to know
- Occasionally you’ll find yourself repeating the same
Given
steps in all of the scenarios in a feature. You can literally move such repeatingGiven
steps to the background, by grouping them under aBackground
section. - A
Background
is run before each scenario, but after any Before hooks. In your feature file, put theBackground
before the firstScenario
Execution order of @before vs Background
- The main thing to understand here is the order of the operations:
- Before Hook 1 -> Before Hook 2 -> … -> Background -> 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.