Replace substrings in Cucumber step argument transforms

Updated . Posted . Visible to the public. Deprecated.

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.

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.

Henning Koch
Last edit
Henning Koch
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2010-09-28 09:10)