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?
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.
Tagged Hooks are much like the scenario hooks, but the only difference is that they are executed before and after the specified tag.
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 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.
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.
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.
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