Monthly Archives: March 2024

Reuse a SpecFlow step definition for Given and When

Have you ever wanted to use a single step definition like I create file '(.*)' from Given and When contexts in a feature file like this?

Scenario: CreateFile
When I create file 'hello.txt'
Then ...
Scenario DeleteFile
Given I create file 'hello.txt'
When I delete 'hello.txt'

Here’s how to have 1 method that implements both the Given and the When I create file '...'

💡 Prefer the newer Reqnroll v3 version?

This post explains the original SpecFlow approach. If you’re using Reqnroll v3 read the updated version instead.

First, create a class like this:

public class GivenWhenAttribute : StepDefinitionBaseAttribute
{
readonly static StepDefinitionType[] types = new[] { StepDefinitionType.Given, StepDefinitionType.When };
public GivenWhen() : this(null) { }
public GivenWhen(string regex) : base(regex, types ) { }
public GivenWhen(string regex, string culture) : this(regex) { Culture = culture; }
}

Then use it in the [Binding] classes like this:

[GivenWhen("I create file '(.*)'")]
public void CreateFile(String Name) { File.Create(Name); }

Voila! 1 step definition method now works for Given and When steps in the feature file.