SpecFlow + Selenium: Basic plumbing

This article is in a series about Selenium and SpecFlow

  1. Introduction
  2. Why bother?
  3. Basic plumbing
  4. Page objects
  5. The engineering behind decent Gherkin files

This series contains an article about how to store and use information when executing a test in a way that lets you write nice Gherkin.  That is a bit more of an advanced article than this one, which aims to show how the basics fit together.  It also refers to page objects, which are explained in an article on page objects.

The one object to rule them all

What you need for Selenium to work is an IWebDriver object.  This is the top-level handle on the web browser instance, that you would need when creating a page object.  When you create the IWebDriver you must say at least which kind of browser you want, e.g:

IWebDriver _driver = new FirefoxDriver();

You can set other properties of the IWebDriver, such as screen width.  The details vary for the different browsers, so I suggest you consult the documentation for different drivers.

A home for your precious

Given how much different code might want to use the IWebDriver, I put it in a context object that can be passed automatically by SpecFlow to whichever classes need it.  I also put the current page object in the same context as they tend to go together:

public class WebContext
{
    public IWebDriver driver { get; set; }

    public PageObject pageObject { get; set; }
}

Creating and destroying

Now that we have a home for the driver, and a way of getting it to all the code that needs it, then we need to have code that creates and destroys the driver.

I find it a good idea to use a fresh browser instance per test scenario.  This is slower than reusing browser instances between test scenarios, but makes it simple to make sure that there is no interference on one test scenario by another.

This means creating and destroying the driver is a candidate for doing via SpecFlow hooks:

[Binding]
public sealed class Hooks
{
    [BeforeScenario]
    public static void GetWebDriver(WebContext webContext)
    {
        webContext.driver = new FirefoxDriver();
    }

    [AfterScenario]
    public static void KillWebDriver(WebContext webContext)
    {
        webContext.driver.Quit();
    }
}

Note that this uses just Firefox, rather than any other browser, and doesn’t vary the screen’s width.  That should be fine to get started, but is something to consider for later.

4 thoughts on “SpecFlow + Selenium: Basic plumbing

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s