An execution context is a scenario’s short-lived memory. It lets later steps use information established by earlier steps without repeating every name or identifier. The context lasts for one scenario execution and is discarded afterward. section 13.1
Remembering a placed order
Suppose Rebecca places order #12342 and then cancels it. A context-independent cancellation step repeats both her name and the order number. If the earlier step remembers the number, the later step can say she cancels “the placed order.” The scenario becomes easier to read without losing track of which order is meant. section 13.1
A simple implementation stores the order number in a step-definition field when the order is placed, then reads that field when it is cancelled. The field supports the narrative; it does not replace the need to make each scenario independent. section 13.1 section 12.4.3
Choose references that remain clear throughout the scenario:
- For a scenario focused on one order, “the order” can identify the current order. section 13.3.2
- For a scenario with multiple orders, distinguish “the completed order” from “the new order.” A step definition can retain the completed order both as the current order and under its specific role. section 13.3.2
- Keep the whole execution context isolated, including relevant external services and resources. A scenario must work alone, in any order, or alongside other scenarios. section 12.4.3
Listing 13.3 Using the step definition class fields for order number
*** StepDefinitions/OrderingStepDefinitions.cs ***
[Binding]
public class OrderingStepDefinitions
{
private int placedOrderNo;
[Given("the customer {string} has placed the order #{int}")]
public void GivenTheCustomerHasPlacedTheOrder(string customerName,
int orderNo)
{
OrderService.PlaceOrder(customerName, orderNo, "Margherita");
placedOrderNo = orderNo; #A
}
[When("the customer {word} cancels the placed order")]
public void WhenTheCustomerCancelsThePlacedOrder(string customerName)
{
OrderService.CancelOrder(customerName,
placedOrderNo); #B
}
}The step-definition field shows how an order number established by one step becomes available to a later step. section 13.1
