Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 37 ยท Scenario Outlines and Data

Doc Strings: Multi-Line Text in Steps

Pass multi-line text such as emails, JSON and logs to a Cucumber step with doc strings: triple-quote syntax, indentation rules, content types and @DocStringType conversion.

A single-line step is a poor container for an email body, a JSON payload or a block of log output. Gherkin offers the doc string: a block of text delimited by three double quotes, placed directly under a step. The step receives the text, with the indentation of the delimiters removed, as one string argument.

GHERKIN
Scenario: Welcome email text
  When Maria registers with the email "[email protected]"
  Then she receives an email with the text
    """
    Hello Maria,

    Welcome to the shop! Your account is ready.

      Order anything, any time.
    Regards,
    The Shop Team
    """

The rules of doc strings

  • The delimiter is """ (or three backticks ```) on its own line. A block starting with """ ends at the next """; one started with backticks ends with backticks. That lets you include the other kind in the text.
  • Indentation is relative. Cucumber removes the indentation of the opening delimiter from every line. In the example above, "Order anything, any time." keeps two extra spaces because it was indented two more than the delimiter.
  • Blank lines are kept.
  • Newlines are normalized to \n, whatever the file uses.
  • After the opening delimiter you may write a content type: """json. It does not change the text; it tells tools (and your converter) how to interpret it.
  • A literal """ inside the text is written \"\"\".
  • It is always the last argument of the step, after any expression parameters, just like a data table. A step can have a doc string or a table, not both.
Java
@Then("she receives an email with the text")
public void sheReceivesAnEmailWithTheText(String expectedBody) {
    assertEquals(expectedBody, mailbox.lastEmail().body());
}

Cucumber also offers a DocString object that exposes getContent() and getContentType().

Parsing and indentation: a stand-in

The following stand-in implements the indentation rule. It takes the raw lines between the delimiters, strips the indentation of the opening delimiter and prints the result with visible markers, so you can see that blank lines and relative indentation survive.

Java Stand-in: extracting a doc string

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Content types and conversion

A doc string is text, but often structured text. With a content type, Cucumber can convert it to an object for you. In Cucumber-JVM you register a converter with @DocStringType:

Java
public class DocStringTypes {
    private final ObjectMapper mapper = new ObjectMapper();

    @DocStringType(contentType = "json")
    public JsonNode json(String docString) throws JsonProcessingException {
        return mapper.readTree(docString);
    }

    @DocStringType
    public Order order(String docString) throws JsonProcessingException {
        return mapper.readValue(docString, Order.class);
    }
}
GHERKIN
When the client posts the order
  """json
  {"customer": "Maria", "lines": [{"sku": "B-1", "qty": 2}]}
  """
Java
@When("the client posts the order")
public void post(JsonNode body) { ... }

With the converter in place the step body receives a parsed tree; otherwise it would receive the raw string.

Parsing JSON is possible on this site, because the Java runner has Jackson on its classpath. The stand-in below plays the role of such a converter: the doc string is JSON, a mapper turns it into a record, and the step logic works on the object.

Java Stand-in: a JSON doc string converted to an object

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Using doc strings well

Doc strings are for inputs and outputs that are naturally text: a message body, a configuration file, a JSON request, an error report. They are a poor fit when:

  • the structure matters to the rule. If the scenario is about a discount on lines, show the lines in a data table, not buried in JSON.
  • the text is long. Fifty lines of JSON drown the point; put the large payload in a resource file and reference it by name: Given the order from "large-order.json".
  • the data is mostly irrelevant. Show only the fields that affect the outcome, and fill in sensible defaults in the step definition.

A doc string is also the right place for text that should be matched exactly, including line breaks, such as a rendered receipt.

Doc strings in outlines

Placeholders work inside doc strings, so an outline can vary one value in a text:

GHERKIN
Scenario Outline: Greeting by language
  When the greeting is generated for "<name>" in "<language>"
  Then the text is
    """
    <greeting>, <name>!
    """

  Examples:
    | name  | language | greeting |
    | Maria | es       | Hola     |
    | Ana   | de       | Hallo    |

Here the same stand-in idea as the outline expander applies: replace <name> in the doc string with the row's value.

Java Stand-in: placeholders inside a doc string

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Pitfalls

  • Trailing whitespace. Editors may strip it; compare with strip() or normalize line endings if you do not care.
  • Windows line endings. Cucumber normalizes them in doc strings, but text returned by your application may use \r\n; normalize before comparing.
  • Over-specified expectations. Asserting on a whole HTML page makes the scenario break on every copy tweak; check only the sentence that matters.
  • Mixing with a table. A step takes either; split into two steps if you need both.

Doc strings, data tables and outlines give you three ways to bring data into a scenario. The final lesson of this chapter shows how to design the data itself so the suite stays small and sharp: Examples tables in depth.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What delimits a doc string?

    Triple double quotes or triple backticks open and close the block.
  2. 2. How is indentation handled inside a doc string?

    Relative indentation is preserved so formatted text keeps its shape.
  3. 3. What does a content type such as json after the opening delimiter do?

    It does not alter the text; a @DocStringType converter can be keyed on it.
  4. 4. When is a doc string a poor choice?

    If lines or fields drive the outcome, show them in a table where they are easy to scan.

Summary

  • A doc string is multi-line text delimited by """ or backticks under a step, passed as the last argument.
  • The opening delimiter's indentation is stripped; relative indentation and blank lines are kept.
  • A content type plus @DocStringType lets Cucumber convert the text into objects such as JSON trees or records.
  • Placeholders work inside doc strings in outlines.
  • Use doc strings for text-shaped data, keep payloads small and normalize line endings before comparing.

Next: Examples Tables in Depth