Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cucumber: When to use tags/hooks vs backgrounds

I was wondering if there is a good argument for or against using backgrounds in cucumber when compared to using tags and hooks.

Having a logged in user before the start of a test could go either like this:

Background:
  Given that I am logged in
Scenario: Lorem ipsum sit amet dolor
[...]

or like this:

@login
Scenario: Lorem ipsum sit amet dolor
[...]

+

before(@login) do
  visit('/admin/login/testuser')
end

Any idea when to favor one over the other?

like image 904
Marc Seeger Avatar asked Apr 03 '12 13:04

Marc Seeger


People also ask

What is the difference between hooks and background in Cucumber?

After hooks will be run after the last step of each scenario, even when there are failing, undefined, pending or skipped steps. 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.

What is the difference between tags and hooks in Cucumber?

Tagged Hooks are much like the scenario hooks, but the only difference is that they are executed before and after the specified tag.

When background is used in Cucumber?

The Background keyword is applied to replicate the same steps before all Scenarios within a Feature File. It should be used for defining simple steps unless we are forced to bring the application to a state which requires complicated steps to be carried out.

Why do we use hooks in Cucumber?

Why Cucumber Hooks? Hooks are blocks of code that run before or after each scenario in the Cucumber execution cycle. This allows us to manage the code workflow better and helps to reduce code redundancy. Hooks can be defined anywhere in the project or step definition layers using the methods @Before and @After.


2 Answers

Background is useful when you provide common customer-readable (non technical) background for your scenarious. It is worth using it if you want to be explicit about this initialization in the text of your Feature.

But sometimes teardown (and setup) logic is an implementation details and is implemented in Before, After or Around hooks (because reader of your spec won't need to know about these technical things).

Summary: use Background if you want to inform reader of your spec of the background and use hooks when background is an implementation details.

In you example Background is the best choice.

like image 124
Aliaksei Kliuchnikau Avatar answered Oct 03 '22 14:10

Aliaksei Kliuchnikau


Definitely the former (IMHO), since it captures everything in the universally readable Gherkin feature file. The tags are only really there to help the runner - they are implementation level. What you describe here is part of the description of what is going on.

like image 28
David M Avatar answered Oct 03 '22 14:10

David M