Establishing context with 'Given'

In the Given, When, Then lifecycle, Given is the place to establish the state of things before you act on the System Under Test (SUT). SpecsFor provides the virtual Given method that you can override to establish context for your specs.

Consider a simple spec like this:

📘

Given a car is started, when the car is stopped, then the engine is stopped.

A spec for this implemented using SpecsFor would look like this:

public class given_a_car_is_started_when_a_car_is_stopped : SpecsFor<Car>
{
    //Given: establish state, in this case, that the car is started.
    
    //When: perform an action, in this case, stopping the car.
    
  //Then: the engine is stopped
}

To establish the state, "Given a car is started," we need to override the Given method, then start the car, which is our system under test:

protected override void Given()
    {
        //Given: establish state, in this case, that the car is started.
        SUT.Start();
    }

Multiple Givens

If you need to use multiple given statements in the same testing class you can do so in the Given method:

protected override void Given()
{
  Given<the_item_is_available>();
  Given<the_item_is_valid>();
  
  base.Given();
}

📘

Pro Tip!

It is not uncommon to need to establish the same state across multiple specs. With SpecsFor, you can easily do this using either context classes or with the SpecsFor convention system


Did this page help you?