Skip to content

Steps Then Context

Jörg Flade edited this page Jun 24, 2026 · 2 revisions

Then — Context


Store a Response Field to Context

Then I store the string of the field {string} in the context {string} for later usage

Reads a JSON field from the response body and stores its value in ScenarioContext under the given key. Once stored, the value is available in any subsequent step that accepts a string argument.

The field argument supports:

  • Simple field name: "id"
  • Nested path: "data.userId"
  • Array element: "items[0].id"
Scenario: Create a resource and use its ID in follow-up requests
  Given that the body of the request is
    """
    { "name": "My Resource" }
    """
  When executing an authorized POST call to "/api/v1/resources" with previously given body
  Then I ensure that the status code of the response is 201
  And I store the string of the field "id" in the context "RESOURCE_ID" for later usage

  Given that the request body in the scenario context map has been reset
  When executing an authorized GET call to "/api/v1/resources/${RESOURCE_ID}"
  Then I ensure that the status code of the response is 200
  And I ensure that the body of the response contains a field "name" with the value "My Resource"

  When executing an authorized DELETE call to "/api/v1/resources/${RESOURCE_ID}"
  Then I ensure that the status code of the response is 204

The stored value also works in body manipulation steps and JSON comparison:

Scenario: Create a parent, then create a child referencing it
  # Create parent
  Given that the body of the request is
    """
    { "name": "Parent" }
    """
  When executing an authorized POST call to "/api/v1/parents" with previously given body
  Then I ensure that the status code of the response is 201
  And I store the string of the field "id" in the context "PARENT_ID" for later usage

  # Create child using the parent ID
  Given that the request body in the scenario context map has been reset
  And that the body of the request is
    """
    { "name": "Child", "parentId": "${PARENT_ID}" }
    """
  When executing an authorized POST call to "/api/v1/children" with previously given body
  Then I ensure that the status code of the response is 201
  And I ensure that the body of the response contains a field "parentId" with the value "PARENT_ID"

In the last Then step, "PARENT_ID" (without ${}) is a context key — the library substitutes the stored value automatically.

Anti-pattern warning: Sharing state between steps via ScenarioContext creates coupling — the step reading the value cannot run independently without the step that wrote it. The Cucumber team documents this as an Anti-Pattern. Use it deliberately, primarily in multi-step end-to-end flows where the cross-step dependency is intentional.

For setting static (non-response) values in context, see Given — Context.

Clone this wiki locally