Read more

How to use triple quotes inside a Cucumber docstring

Dominik Schöler
May 03, 2016Software engineer at makandra GmbH

Cucumber's docstrings let you add long strings to a step like this:

# foo.feature
Given this text:
"""
First line
Second line

Second Paragraph
"""

# foo_steps.rb
Given /^this text:$/ |docstring|
  puts docstring.split
end
Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

You see these neat triple double quotes ("""). Now what to do when you need your docstring to contain triple double quotes, too?

# Does not work:
Given this text:
"""
Docstrings work like this:
  """
  Docstring example
  """
You see?
"""

Update: Official solution

You can escape the inner quotes to tell Gherkin to ignore them:

# Does not work:
Given this text:
"""
Docstrings work like this:
  \"\"\"
  Docstring example
  \"\"\"
You see?
"""

Self-made Solution

Cucumber Transforms to the rescue! Transforms are run on step arguments after parsing the feature file, but before passing them to the step definition.

To fix the problem above, replace the triple double quotes inside the docstring with triple single quotes:

# Does not work:
Given this text:
"""
Docstrings work like this:
  '''
  Docstring example
  '''
You see?
"""

Now create features/support/transforms.rb with this content:

# Only a single Transform is executed per step argument
# Transforms are matched from bottom (first) to top (last)

# Enables nested docstrings (""") by allowing to use triple single quotes. This
# Transform turns them back into triple double quotes.
Transform /^.*'''.*$/ do |string|
  string.gsub /'''/, '"""'
end

Voilà! The step definition will now receive the String with triple double quotes.

Dominik Schöler
May 03, 2016Software engineer at makandra GmbH
Posted by Dominik Schöler to makandra dev (2016-05-03 09:10)