Search code examples
testingintegration-testinggherkin

Best way to write scenario in gherkins


Just started with gherkins and I need to write gherkins scenarios for my Rest API.

There is a scenario where user inputs customer Id and order Id and the rest service links order Id with customer Id based on some checks. It then returns the complete details of order.

The gherkins scenario that I quoted is as follows :

Scenario: Associate an order to customer
    When User provides order to attach to customer
    Then User should get the associated order details

Now if the Customer or order id is invalid, the rest call will respond with the corresponding error message.

Should I use GIVEN to ensure the customer and order Id exist?

GIVEN : Customer exit with Id "abc" AND Order exit with Id "bcd"

Is there any significance of GIVEN here ? What is the best way to write this example scenario ?


Solution

  • Yes, you should supply a Given that creates a customer and order. You actually want two steps for this, one to create the customer, and another to create the order:

    Scenario: Associate an order to customer
        Given a customer exists
        And an order exists
        When User provides order to attach to customer
    

    I think you need two scenarios here, actually. One asserting the customer and order are associated with each other, and another one to assert the details:

    Scenario: Associate an order to customer
        Given a customer exists
        And an order exists
        When User provides order to attach to customer
        Then the customer should be associated with the order
    
    Scenario: Retrieving the order details after associating a customer to an order
        Given a customer exists
        And the following order exists:
            | Field | Value |
            | A     | 1     |
            | B     | 2     |
            | C     | 3     |
        When User provides order to attach to customer
        Then User should receive the following order information:
            | Field | Value |
            | A     | 1     |
            | B     | 2     |
            | C     | 3     |
    

    Now each test only has one reason to fail. If the order doesn't get associated with the customer, but returns the order info anyhow, then the scenario concerned with the customer being associated with the order will fail. The scenario asserting the order details will continue to pass. This helps you debug the test failure.

    Furthermore, if the requirements for the order details being returned change, but the requirements to associate a customer with an order do not change, then the scenario about retrieving the order details will fail, while the scenario about associating the customer with the order continues to pass. Again, this helps narrow down the point of failure in the application.