Writing our first scenario
Next, we'll write our first scenario and steps. As a reminder, the scenario is "If the client sends a POST request to /users with an empty payload, our API should respond with a 400 Bad Request HTTP status code, and a JSON object payload containing an appropriate error message".
Feature: Create User
Clients should be able to send a request to our API in order to create a
user. Our API should also validate the structure of the payload and respond
with an error if it is invalid.
Scenario: Empty Payload
If the client sends a POST request to /users with a unsupported payload, it
should receive a response with a 4xx status code.
When the client creates a POST request to /users
And attaches a generic empty payload
And sends the request
Then our API should respond with a 400 HTTP status code
And the payload of the response should be a JSON object
And contains a message property which says "Payload should not be empty"
We have broken the scenario down into modular units called steps and prefixed them with the Gherkin keywords. Here, we've used the keywords When, Then, and And, although we could have used any of the five keywords; we chose these because it makes the specification more readable.
Generally, you can group steps into three categories:
- Setup: Used to set up the environment in preparation for an action to be executed. Usually, you'd use the Given keyword to define setup steps.
- Action: Used to execute an action, which is usually the event we are testing for. You'd typically use the When keyword to define action steps.
- Assertions: Used to assert whether the actual outcome of the action is the same as the expected outcome. Usually, you'd use the Then keyword to define assertion steps.
Furthermore, you can use the And and But keywords to chain multiple steps together and make the specification more readable. But, remember that all step keywords are functionally equivalent.