Read more

Replace substrings in Cucumber step argument transforms

Henning Koch
September 28, 2010Software engineer at makandra GmbH

Transform is no longer supported in Cucumber 3.

Cucumber step argument transforms Show archive.org snapshot can be a powerful way to make your steps more flexible.

Illustration money motivation

Opscomplete powered by makandra brand

Save money by migrating from AWS to our fully managed hosting in Germany.

  • Trusted by over 100 customers
  • Ready to use with Ruby, Node.js, PHP
  • Proactive management by operations experts
Read more Show archive.org snapshot

Note however that if your transform only matches a substring (no ^ and $ markers at the beginning and end), you are still expected to return a replacement for the whole string that was piped through the transform. If you don't do that, you will truncate that string and possibly make the calling step match where it should not.

Let's say you want a transform that replaces substrings like "translate:foo" by the I18n translation for "foo". This transform will incorrectly discard characters left and right from "translate:foo":

Transform /\btranslate:(.+?)\b/ do |key|
  I18n.t(key)
end

A more correct version of that transform would be this:

Transform /^(.*?)\btranslate:(.+?)\b(.*?)$/ do |left, key, right|
  left + I18n.t(key) + right
end

If you'd like to replace multiple substrings in the same match, you might even want to transform every captured string:

Transform /^(.*)$/ do |str|
  str.gsub(/\btranslate:(.+?)\b/) do |match|
    I18n.t($1)
  end
end

Other than with step definitions, Cucumber does not mind multiple transforms matching the same captured string.

Posted by Henning Koch to makandra dev (2010-09-28 11:10)