Background Sections
A Background section belongs to a feature file and runs before every scenario in that file, automatically. It is the place for setup that every scenario in the feature shares: creating a logged-in user, seeding reference data, or pointing the test at a sandbox URL. Because it runs per scenario rather than once per file, each scenario starts from a clean, well-defined state.
Syntax
Feature: Shopping cart
Background:
Given the store is open
Given an empty shopping cart
Scenario: Add an item
When I add 2 cucumbers to the cart
Then the cart total is 3.50
Scenario: Checkout with an empty cart
When I try to checkout
Then I see the message "cart is empty"
How It Executes
from behave import given
@given("the store is open")
def step_impl(context):
context.store_open = True
@given("an empty shopping cart")
def step_impl(context):
context.cart = []
For each scenario, behave first runs the background steps, then the scenario steps. If a background step fails, the scenario is reported as failed and its own steps are not executed. The context object is fresh for every scenario, so background setup never leaks into the next run.
Keep Backgrounds Small
Background steps multiply across every scenario, so expensive setup slows the whole suite. Keep the background to cheap, essential state and move scenario-specific data into the scenario itself. If only some scenarios need the setup, a tag-based grouping or a plain Given step inside those scenarios is the better fit.
Summary
Backgrounds define the shared precondition for all scenarios of a feature. They run before each scenario, fail fast on error, and must stay small because their cost is paid by every scenario in the file.