Creating a Scenario with the And and But keywords
When we specify a business requirement, sometimes there are multiple pre-conditions, user actions, and expected outcomes. So how do we write these specifications in Cucumber?
Getting ready…
Based on what we have learned so far we know how to create Scenarios with one Given, When, and Then keyword. Now, if we need to add multiple Steps, then we can update our Feature file like this:
Feature: login Page In order to test login page As a Registered user I want to specify the login conditions Scenario: without and & but Given user is on Application landing page Given Sign in button is present on screen When user clicks on Sign in button Then user can see login screen When user enters "ShankarGarg" in username field When user enters "123456" in password field When user clicks Sign in button Then user is on home page Then title of home page is "GitHub"
The problem here is that the keywords Given
, When
, and Then
are repeated and the readability is thus affected. Having readable Feature files is one of biggest advantages of Cucumber. So how do we maintain the readability of Feature files? Let's figure this out in this recipe.
How to do it…
In this recipe, we are going to add one more Scenario and will use the And
and But
keywords:
Feature: login Page In order to test login page As a Registered user I want to specify the login conditions Scenario: with and & but Given user is on Application landing page And Sign in button is present on screen When user clicks on Sign in button Then user is displayed login screen When user enters "ShankarGarg" in username field And user enters "123456" in password field And user clicks Sign in button Then user is on home page And title of home page is "GitHub" But Sign in button is not present
How it works…
The And
and But
keywords will be useful here. These keywords help to increase the expressiveness and readability of the Feature file:
- And: This is used for statements that are an addition to the previous Steps and represent positives statements.
- But: This is used for statements that are an addition to previous Steps and represent negative statements.
Note
In a Step Definitions file, And
and But
are listed as Given/When/Then, the keyword that they appear after. There are no And
and But
keywords in Step Definitions.