Search code examples
javacucumbergherkincucumber-java

How to re-use steps in Feature file /Duplicate step definitions/


I have a few Scenarios in a Feature file with repeatable steps ('I am on Login form' and 'click on login button'). Test failed with error Duplicate step definitions in Steps.LoginSteps. Is it possible to somehow to reuse duplicated steps?

Feature: LoginFeature

Scenario: Login with valid username and password
    Given I am on Login form
    And I enter valid username and password
    And click on login button
    Then I should see the main page


  Scenario: Login with invalid username and password
    Given  I am on Login form
    And I enter invalid email username and password
    And click on login button
    When modal error is displayed
    Then click on Ok button
    And I should see the login form 

Solution

  • You could use Background for steps that are common for all the scenarios in the same feature (the goal is to avoid repetition) Example:

    Feature: LoginFeature
    
    Background:
    
    Given I am on Login form
    
    Scenario: Login with valid username and password
    
        And I enter valid username and password
        And click on login button
        Then I should see the main page
    
    
      Scenario: Login with invalid username and password
    
        And I enter invalid email username and password
        And click on login button
        When modal error is displayed
        Then click on Ok button
        And I should see the login form 
    

    Also you could modify the step for button click in order to pass a parameter. This way you will have only one step for button click that you could use in different scenarios passing different parameter (login, Ok etc).

    Example:

    Click on "login" button