And and But keyword in Cucumber

Profile picture for user devraj

Our Business requirement does not only consist of a single pre-condition, user action, or expected outcomes. We mention Given, When, and Then more than once for a few scenarios. 

Cucumber will not restrict you to using Given, When, and Then multiple times, but it is good to avoid using the same keyword in the following line for readability and expressiveness.

AND keywords in Cucumber

The And keyword is used to add conditions to your steps or add more detail to an action. It's an addition to the previous statement. AND is used to add more conditions to Given, When and Then statements. It represents a positive statement. 

BUT keyword Cucumber

BUT keyword is used to add negative type comments. It is good to use when your step describes a condition that is not expected. For example, when you expect some text or element to not be present on the page.​

Example of Scenario without And and But

@userflow
Feature: Registration, Login and MyAccount

  @regression @testing
  Scenario: Verify Login Functionality
    Given I am on the homepage
    Given I should see "Sign in" link
    When I follow "Sign in" link
    When I fill "email address" with "goswami.tarun77@gmail.com"
    When I fill "password" with "tarun@123"
    When I click "sign in" button
    Then I should see "My Account" Heading
    Then I should see "my account" link
    Then I should not see "Login" Heading

The problem with the above scenario is that Given, When, and, Then are repeated multiple times, and readability is affected.

Example of Scenario with And and But

@userflow
Feature: Registration, Login and MyAccount

  @regression @testing
  Scenario: Verify Login Functionality
    Given I am on the homepage
    And I should see "Sign in" link
    When I follow "Sign in" link
    And I fill "email address" with "goswami.tarun77@gmail.com"
    And I fill "password" with "tarun@123"
    And I click "sign in" button
    Then I should see "My Account" Heading
    And I should see "my account" link
    But I should not see "Login" Heading