Q4 of 40 · Karate

What is the difference between Background and Scenario in Karate?

KarateJuniorkaratebackgroundscenariofeature-filebdd

Short answer

Short answer: Background runs its steps before every Scenario in the feature file — use it for shared setup like setting the base URL, defining auth headers, or common variables. Scenario contains the actual test steps. Unlike JUnit @BeforeEach, Background is part of the feature file itself and its steps appear inline in the HTML report.

Detail

Background — pre-scenario setup shared across all scenarios in a file:

Background:
  * url 'https://api.example.com'
  * def authHeader = { Authorization: 'Bearer ' + token }

These steps run before every Scenario in the file. They are visible in the report as steps that executed before the scenario body, which makes debugging easier than a hidden Java @BeforeEach.

Scenario — the actual test case:

Scenario: Delete user requires admin role
  Given path '/users/42'
  When  method DELETE
  Then  status 403

Key differences:

Background Scenario
Runs Before every Scenario Once, for one test
Purpose Shared setup Test logic
Variables Available to all scenarios Scoped to this scenario
In reports Shown as pre-steps Main scenario body

What does NOT belong in Background: assertions, test-specific request bodies, scenario-specific variable assignments. Keep Background minimal — URL + auth is enough.

// EXAMPLE

order-api.feature

Feature: Order Management

  Background:
    * url 'https://api.example.com'
    * def auth = call read('classpath:helpers/get-token.feature')
    * header Authorization = 'Bearer ' + auth.token

  Scenario: Get order returns 200
    Given path '/orders/1'
    When  method GET
    Then  status 200
    And   match response.id == 1

  Scenario: Get missing order returns 404
    Given path '/orders/99999'
    When  method GET
    Then  status 404
    And   match response.error == '#string'

  # Background URL and auth run before both scenarios above

// WHAT INTERVIEWERS LOOK FOR

Understanding that Background is not just documentation — it executes before every scenario. Knowing what belongs in Background (base URL, auth) vs what should stay in the scenario (test-specific data, assertions).

// COMMON PITFALL

Putting complex data setup in Background when only one scenario needs it — all scenarios pay the setup cost even if they don't need it. Per-scenario setup belongs in the scenario body or a called helper feature.