Posted over 3 years ago. Visible to the public.

How to use triple quotes inside a Cucumber docstring

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

Copy
# foo.feature Given this text: """ First line Second line Second Paragraph """ # foo_steps.rb Given /^this text:$/ |docstring| puts docstring.split end

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

Copy
# 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:

Copy
# 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:

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

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

Copy
# 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.

By refactoring problematic code and creating automated tests, makandra can vastly improve the maintainability of your Rails application.

Owner of this card:

Avatar
Dominik Schöler
Last edit:
over 3 years ago
by Dominik Schöler
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Dominik Schöler to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more