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