SpecFlow and Selenium-Share data between different step definitions or classes

2.1k views Asked by At

I just started using SpecFlow along with Selenium & N Unit.

I have a basic question, maybe I know the answer to it, but want to get it confirmed.

Consider, there are two features - Register and Add new transaction. Two separate features with their respective step definitions. How do I share the IWebDriver element across both the features?

I do not want to launch a new browser again and add a transaction. I want to execute both as a flow.

My thoughts are this functionality is not allowed using SpecFlow as basic use of feature-based testing is violated as trying to run two features in the same session. Will context injection assist help in this case?

1

There are 1 answers

9
Sam Holder On BEST ANSWER

What you want to do is a bad idea. you should start a new browser session for each feature, IMHO.

There is no guarantee in what order your tests will execute, this will be decided by the test runner, so you might get Feature2 running before Feature1.

In fact your scenarios should be independent as well.

you can share the webdriver instance between steps as in this answer but you should use specflows other features like scenario Background to do setup, or definign steps which do your comman setup.

EDIT

We have a similar issue with some of our tests and this is what we do:

We create a sceanrio for the first step

Feature: thing 1 is done

Scenario: Do step 1
    Given we set things for step 1 up
    When we execute step 1
    Then some result of step one should be verified

Then we do one for step 2 (which lets assume relies on step 1)

Feature: thing 2 is processed

Scenario: Do step 2
    Given we have done step 1
    And we set things for step 2 up
    When we execute step 2
    Then some result of step 2 should be verified

This first step Given we have done step 1

is a step that calls all the steps of feature 1:

[Given("we have done step 1")]
public void GivenWeHaveDoneStep1()
{
     Given("we set things for step 1 up");
     When("we execute step 1");
     Then("some result of step one should be verified");
}

Then if we have step 3 we do this:

Feature: thing 3 happens

Scenario: Do step 3
    Given we have done step 2
    And we set things for step 3 up
    When we execute step 3
    Then some result of step 3 should be verified

Again the Given we have done step 2 is a composite step that calls all the steps in the scenarion for step 2 (and hence all the steps for step 1)

[Given("we have done step 2")]
public void GivenWeHaveDoneStep2()
{
     Given("we have done step 1");
     Given("we set things for step 2 up");
     When("we execute step 2");
     Then("some result of step 2 should be verified");
}

We repeat this process so that when we get to step 5, it is running all the steps in the correct order. Sometimes one we get to step 5 we @ignore the previous 4 steps as they will all be called by step 5 anyway.