As I know, the @Before hooks are executing before every scenario(s), and now I've met with the Background tag, but it seems to me it has the exact same functionality as the @Before tag except it's own steps. Can anybody explain what is the diff.s in real life? when I have to use Background instead of Before?
Use Background when you provide customer-readable pre-conditions to your scenarios. Use Before when you have to do some technical setup before your scenarios.
A Background allows you to add some context to the scenarios that follow it. It can contain one or more Given steps, which are run before each scenario, but after any Before hooks. A Background is placed before the first Scenario / Example , at the same level of indentation.
Using Background in CUCUMBER, we can make the feature file more readable and less complex in lieu of writing steps over and over again for each scenario. When we execute the feature, at run time, the steps in Background are executed in the beginning of each scenario.
Use scenario outlines to group examples that share the same structure, and put common data in the scenario instead of the example tables. Use background sections to expose contextual information for examples that do not share the same structure.
According to the Cucumber documentation, here is what Before
does:
Before hooks will be run before the first step of each scenario. They will run in the same order of which they are registered.
And here is what Background
does:
Background allows you to add some context to the scenarios in a single feature. A Background is much like a scenario containing a number of steps. The difference is when it is run. The background is run before each of your scenarios but after any of your Before Hooks.
In facts, as you noticed already, their structures are a little bit different. The common practice is to use them as follows:
Background
when you provide customer-readable pre-conditions to your scenariosBefore
when you have to do some technical setup before your scenarios But the main thing to understand here is the order of the operations:
Before Hook 1 -> Before Hook 2 -> ... -> Background -> Scenario
They just represent different levels of pre-conditions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With