An ensure method creates a step’s functional prerequisite only when the scenario has not already supplied it. This lets one step work with either a default prerequisite or an explicit, scenario-specific one. section 16.3
A practical implementation follows these guidelines:
- Put the ensure method on a shareable scenario context, and name it with the “Ensure” prefix. section 16.3
- Check whether the prerequisite exists before creating it; repeated calls should be safe. section 16.3
- Avoid chains of prerequisites that the scenario does not directly require; they make the code harder to understand. section 16.3
Listing 16.14 The EnsureOrderPlaced helper method and its usage
*** Support/OrderingContext.cs ***
public class OrderingContext(OrderingApiDriver orderingApiDriver)
{
public int? CurrentOrderNo { get; set; }
public async Task EnsureOrderPlaced() #A
{
if (CurrentOrderNo == null)
{
var orderRequest = new PlaceOrderRequestObjectMother().Build();
var placedOrder = await orderingApiDriver.PlaceOrder(orderRequest)
.Execute();
CurrentOrderNo = placedOrder.OrderNo;
}
}
}
*** StepDefinitions/CustomerCollectionStepDefinitions.cs ***
[When("they choose to collect their order")]
public async Task WhenTheyChooseToCollectTheirOrder()
{
await orderingContext.EnsureOrderPlaced(); #B
await orderingApiDriver
.SetForCollection(orderingContext.CurrentOrderNo
?? throw new InvalidOperationException("No current order"))
.Execute();
}See the helper and its use in a collection-order step: it places a default order only when the context has no current order. section 16.3
