16

Is there a way to have SpecFlow reuse Step Definitions?

In other tools I have used a GivenWhenThen base class that contains methods such as

WhenAnOrderIsCreated -- this inits a protected order member to be used by inheriting classes.

Just cant seem to get this working with SpecFlow (doesnt seem to like inheritance)

Is there a way to share steps across features?

Many thanks

Chris McKelt
  • 1,378
  • 2
  • 17
  • 38

1 Answers1

29

Why yes it's possible - check out the calling steps from step feature (https://specflow.org/documentation/Calling-Steps-from-Step-Definitions/)

In short you create a step definition class that inherits from Steps like this:

[Binding]
public class CallingStepsFromStepDefinitionSteps : Steps
{}

And then you can simply call other steps like this:

[Given(@"I am logged in")]
public void GivenIAmLoggedIn()
{
     Given("I am on the index page");
     When("I enter my unsername nad password");
     And("I click the login button");
     incStepCount();
}

I hope I understood your question correctly and that this was an answer to it

Marcus Hammarberg
  • 4,762
  • 1
  • 31
  • 37
  • 1
    Users should be aware that using this will leave the 'CurrentStep' as the last type of step called in the method and not the type of step the method is bound to. This is important as any `And` steps that follow will assume the 'CurrentStep' type, which may have changed. In the example above an `And` step executed directly after calling `Given I am logged in` will assume the next step is a when and not a `Given` (as the last step called in the method is a `Given`). – Sam Holder Oct 20 '15 at 13:55
  • 2
    It's better to call the C# method directly rather than via, for example, "Given("I am on the index page");". That way changing the step descriptions will not cause these calls to fail. – Sachin Kainth Nov 23 '16 at 14:21
  • 1
    We originally used steps in this way, but its quite hard to debug when something goes wrong or fails because it appears to just skip over the failing step and gives a generic error message, we have now switched to context steps as described here http://stackoverflow.com/questions/38723867/navigate-to-specflow-step-from-within-step-definitions/38814234#38814234 – Sirk Apr 19 '17 at 14:03
  • 1
    Note: This feature was removed in SpecFlow 4.0. https://github.com/SpecFlowOSS/SpecFlow/issues/1733 – user3819197 Sep 08 '22 at 07:36