Specflow and reusing steps from another feature

user2846391 picture user2846391 · Oct 4, 2013 · Viewed 16.2k times · Source

I am trying to learn specflow and right now. Currently I have 2 feature files.

In the second feature file, I am reusing a step from the first feature file.

Specflow automatically recognizes the step from the first feature file and when specflow generated the steps for my second feature, it was smart and did not regenerated the step I am reusing.

But this step is a Given step and it initializes a member field of the feature class.

Without using scenario context, how can I reuse a step from another feature file that initialize a member of the class ?

Edit

For example, if you have a Given I am logged in that is used in several feature file. This "Given" creates a user object which is logged and store it as a member in .cs feature file.

When you use the same Given in another .feature, Specflow does not regenerate it in the correspond .cs file. When you debug the a scenario which is using it, it executes it from the first .cs file.

But I can't access the member of the first .cs feature file. I am planning to use a static member but perhaps there is another solution ?

Thanks a lot.

Answer

AlSki picture AlSki · Oct 7, 2013

The big point here is that Step Bindings are global. This seems to be a common anti-pattern with Specflow that lots of people goes through. Initially you have a phase of creating hierarchies of binding classes that match your feature files. Instead you need to create collaborating classes that don't match the features but instead produce features through their collaboration.

It's just like your main application code. You wouldn't have a single ATMMachineCashWithdrawal class, instead you would have an ATMMachine, that has a PINCodeCheck, an OperationSelection and a WithdrawalOperation. Those objects collaborate to make your "I want to withdraw cash" feature, and when you add a "Check my balance" feature, you can reuse everything except the WithdrawalOperation.

The bindings in Specflow are the same. We might have an ATMTester that knows how to setup an ATMMachine and supplies your Given I have a cash machine full of cash and you could have a CustomerTester that knows how to fake/mock/setup your account balance with Given my account has loads of money in it.

Fortunately SpecFlow provides ways to collaborate the classes too. Have a look at http://www.specflow.org/documentation/Sharing-Data-between-Bindings/