jeudi 7 décembre 2017

c# SpecFlow BeforeScenario hooks

I'm programming several Scenario's in one Feature file. I'm using one big Steps file to bind the Scenario steps to code.

For example my Feature file looks like this:

Feature: Feature1
    Description of feature1

@TagA @TagB
Scenario: Scenario1
    Given Some form
    When I press the submit button
    Then I end up at a page

@TagA
Scenario: Scenario2
    Given Some form
    When I press cancel
    Then I should end up at a different page

And my Step file looks like this:

using System;
using TechTalk.SpecFlow;

namespace UpdateServer.AcceptanceTests.StepFiles
{
    [Binding]
    [Scope(Feature = "Feature1")]
    public class Feature1Steps : SeleniumTestsBaseClass
    {
        [BeforeScenario("TagA")]
        public void BeforeScenarioTagA()
        {
            // prepare some stuff
        }

        [BeforeScenario("TagB")]
        public void BeforeScenarioTagB()
        {
            // prepare some other stuff
        }

        [Given(@"Some form")]
        public void GivenSomeForm()
        {
            // navigate to form
        }

        [When(@"I press the submit button")]
        public void WhenIPressTheSubmitButton()
        {
            // press submit button
        }

        [When(@"I press cancel")]
        public void WhenIPressCancel()
        {
            // press cancel button
        }

        [Then(@"I end up at a page")]
        public void ThenIEndUpAtAPage()
        {
            // check url
        }

        [Then(@"I should end up at a different page")]
        public void ThenIShouldEndUpAtADifferentPage()
        {
            // check url
        }
    }
}

Notice that my step files inherits from a base class which has some general given,when,then bindings and one AfterScenario which closes the webdriver.

Now when I run Scenario2 it will execute the BeforeScenario of TagB as well. Ofcourse I don't want this behaviour, why does SpecFlow still execute the TagB code in this context? And how can I stop it from doing that?

Edit

The SeleniumTestsBaseClass is used to initialize a Selenium WebDriver in the constructor of this base class. This is the reason why the Scope has been added to the steps class because all my step classes inherit from the base class. Removing this Scope attribute results in a WebDriver to be opened for every step file there is, even when only one test is being run.

Follow up question: What's the best place to initialize my WebDriver without risking it being opened more times than necessary?

Aucun commentaire:

Enregistrer un commentaire