Search code examples
loopsbehat

Repeat the same scenario with a variable


I am testing the user rights of one web app's APIs with Behat. I need to be sure that several roles cannot access to some APIs. Therefore, I need to check that these roles receive a Forbidden response from the APIs. This works well, but as there are 8 different roles, my feature file is getting huge because I repeat all the steps for every role..

My current feature is written as follow:

Feature: Accounting

  @accounting
  Scenario: I want to see the accounting
    Given I have the role of "sales"
    When I want to get the accounting
    Then I should get a forbidden response
    When I want to get the balance sheet
    Then I should get a forbidden response
    When I want to get the income statement
    Then I should get a forbidden response

    Given I have the role of "project"
    When I want to get the accounting
    Then I should get a forbidden response
    When I want to get the balance sheet
    Then I should get a forbidden response
    When I want to get the income statement
    Then I should get a forbidden response

    Given I have the role of "support"
    When I want to get the accounting
    Then I should get a forbidden response
    When I want to get the balance sheet
    Then I should get a forbidden response
    When I want to get the income statement
    Then I should get a forbidden response

    ...

Only the role name changes, everything else is same. I would like to know if there is a way to re-execute one scenario several times but with different input? Or may be there is a better way to handle such situations?


Solution

  • That's what scenario outlines are for:

      Scenario Outline: I want to see the accounting
        Given I have the role of "<role>"
        When I want to get the accounting
        Then I should get a forbidden response
        When I want to get the balance sheet
        Then I should get a forbidden response
        When I want to get the income statement
        Then I should get a forbidden response
    
        Examples:
          | role    |
          | sales   |
          | project |
          | support |