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 web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
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)