Building Enterprise JavaScript Applications
上QQ阅读APP看书,第一时间看更新

Using scenario outlines

In our second scenario, we have three steps that are very similar to the steps defined for our first scenario. So far, we have simply been copying and pasting those step definitions and making small changes to them. Repetition or duplication is never good when it comes to code; so instead, we can define a scenario outline, which acts as a template scenario with placeholder variables that we can plug in. For example, we can combine these two scenarios into a scenario outline as follows:

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 Outline: Bad Client Requests

If the client sends a POST request to /users with an empty payload, it
should receive a response with a 4xx Bad Request HTTP status code.

When the client creates a POST request to /users
And attaches a generic <payloadType> payload
And sends the request
Then our API should respond with a <statusCode> HTTP status code
And the payload of the response should be a JSON object
And contains a message property which says <message>

Examples:

| payloadType | statusCode | message |
| empty | 400 | "Payload should not be empty" |
| non-JSON | 415 | 'The "Content-Type" header must always be "application/json"' |
| malformed | 400 | "Payload should be in JSON format" |

First, we changed the keyword from Scenario to Scenario Outline and added placeholders (enclosed in <>). Then, we use the Examples keyword to supply these placeholders with actual values in the form of a datatable, which is simply columns of values separated by the pipe character (|). Now, our Cucumber specification is a lot less repetitive!

After each refactoring step, we should take care to ensure that we didn't break anything. So run our tests again and check they still pass.