liveBook · Manning

Ensure pattern

As explained in Effective Behavior-Driven Development

A code-structuring pattern that lets a step definition create an implicit functional prerequisite only when no explicit prerequisite exists.

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

How Effective Behavior-Driven Development covers it

How deep it goes
Defines the pattern, shows a context helper implementation, and warns against complex prerequisite chains.
Examples
Uses customer collection scenarios with implicit or explicit orders and an EnsureOrderPlaced helper.
What you can do after
Build it from scratch by adding a context helper that creates a prerequisite only when one is absent.
How it connects
Ties step definitions and scenario context classes to functional prerequisites and scenario reuse.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Effective Behavior-Driven Development. The section links point to the parts of the book it draws on.