← Back to libraryQuestion 253 of 468
šŸ„’Cucumber / BDDIntermediate

Background

šŸ“Œ Definition:

A Background is a set of steps run before EACH scenario in a feature file, used to define common preconditions once instead of repeating them in every scenario.

šŸ“– Detailed Explanation:

If every scenario in a feature starts with the same Given steps (e.g. 'Given the user is logged in' and 'Given the catalog has products'), you move them into a Background: block at the top of the feature. Cucumber executes the Background before each scenario, keeping scenarios focused on what's unique. Backgrounds should be short and contain only genuine shared context — not incidental setup or actions/assertions. Overloading a Background hurts readability and hides important preconditions. It's the Gherkin equivalent of a beforeEach for shared arrange steps.

šŸ”‘ Key Points:
  • Background runs before EACH scenario in the feature
  • Extracts common Given preconditions (DRY)
  • Keep it short — context only, not actions/assertions
  • Gherkin equivalent of beforeEach
šŸŒ Real-World Example:

Background:\n Given the user is logged in\n And the cart is empty\n— shared by every checkout scenario, so each scenario starts from the same known state without repeating those lines.

šŸŽÆ Scenario-Based Interview Question:

When should you use a Background versus a hook (@Before) for setup, and what's a common misuse?