Backgrounds - nripendra/xGherkin.net GitHub Wiki

Backgrounds

Background in gherkin adds some context to the scenarios in a single feature. A Background is defined very much like a scenario containing a number of steps, but without scenario description text. The background effectively gets applied to before each scenarios in the feature. Talking in terms of code, a background runs before each senario.

Hence background is a handy place where we can initialize a context that are common to each and every scenarios in feature.

Syntax

In gherkin background is written as follows:

Feature: Profile edit support
  A logged in user must be able to edit his profile, 
  but shouldn't be able to edit other user's profile

  Background:
    Given I'm logged in as "Bob"

  Scenario: Bob tries to edit own profile
    Given I'm in profile page of "Bob".
    When I click on edit link
    Then I should see editable form for my details

  Scenario: Bob tries to edit Sam's profile
    Given I'm in profile page of "Sam".
    Then I should not see an edit link

So, here background effectively specifies a precondition that is common to both the scenarios in the feature. It's now not necessary to mention 'Given I'm logged in as "Bob"' in both the scenario as it is a background.

How to do it in xGherkin.net?

Nice question! Initial thought was to leave xunit convention as it is, i.e. background would have to be declared as class constructor. But to remain as close to gherkin as possible, xGherkin.net supports a special method named 'BackGround'. Meaning if you name your method as 'Background' it is treated specially by xGherkin.net and executed before executing each scenario.

[Feature("Profile edit support",
  @"A logged in user must be able to edit his profile, 
  but shouldn't be able to edit other user's profile")]
public class ProfileEditSupport
{
  public void Background()
  {
    "Given I'm logged in as \"Bob\"".Do(_ => 
    {
      
    });
  }

  [Scenario("Bob tries to edit own profile")]
  public void EditOwnProfile()
  {
    "Given I'm in profile page of \"Bob\"".Do(_ => 
    {
    });

    "When I click on edit link".Do(_ => 
    {
    });

    "Then I should see editable form for my details".Do(_ => 
    {
    });
  }

  [Scenario("Bob tries to edit Sam's profile")]
  public void EditOthersProfile()
  {
    "Given I'm in profile page of \"Sam\"".Do(_ => 
    {
    });

    "Then I should not see an edit link".Do(_ => 
    {
    });
  }
}