</>

Technology

Cucumber

Difficulty

Beginner

Interview Question

What are the various keywords used in Cucumber for writing a scenario?

Answer

Gherkin Keywords for Writing Scenarios

Step Keywords (Most Important)

KeywordPurposeExample
GivenPrecondition — sets initial contextGiven the user is on the login page
WhenAction — event that triggers behaviorWhen the user enters valid credentials
ThenOutcome — expected result / assertionThen the dashboard should be displayed
AndAdds another step of the same typeAnd the user clicks the Login button
ButNegative continuationBut the error message should not appear

Structural Keywords

KeywordPurpose
FeatureDescribes the feature being tested
ScenarioA single test case
Scenario OutlineParameterized test with multiple data sets
BackgroundCommon steps before each scenario
ExamplesData table used with Scenario Outline

Complete Example

Gherkin
Feature: Shopping Cart

  Background:
    Given the user is logged in
    And the user is on the product page

  Scenario: Add single item to cart
    When the user clicks "Add to Cart" for "Laptop"
    Then the cart count should show "1"
    And the cart total should be "$999"
    But the checkout button should not be disabled

  Scenario Outline: Add multiple products
    When the user adds "<product>" to the cart
    Then the cart should contain "<product>"
    And the price shown should be "<price>"

    Examples:
      | product  | price  |
      | Laptop   | $999   |
      | Phone    | $599   |
      | Tablet   | $399   |

Tips

  • And / But inherit the type of the preceding step (Given/When/Then)
  • Use And to keep scenarios readable without repeating Given/When/Then
  • Steps should describe business behavior, not implementation details

Follow AutomateQA

Related Topics