Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(Cucumber) What's the difference between Background and Before tag

Tags:

tags

cucumber

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?

like image 539
Gregito Avatar asked Jun 02 '16 07:06

Gregito


People also ask

What is the difference between before and background in Cucumber?

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.

What is background tag in Cucumber?

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.

What are the advantages of using background in Cucumber?

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.

What is the difference between background and scenario outline?

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.


1 Answers

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:

  • 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

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.

like image 179
meucaa Avatar answered Oct 13 '22 19:10

meucaa