Specifying constants in Cucumber Transforms

Posted . Visible to the public.

Usually a cucumber step definition will have some sort of regular expression capture:

Given(/^I have (\d+) dollars in my account$/) do |amount|
  #step logic
end

As the Given is specified above the amount argument will still be a string. A Transform method can convert that to a number (instead of doing the conversion directly in the step definition itself:

Transform(/^\d+$/) do |number|
  number.to_i
end

Cucumber also supports an even more awesome capability: The ability to name transforms and use them in step captures:

CAPTURE_CASH_AMOUNT = Transform(/^\d+$/) do |digits|
  digits.to_i
end

#And the step definition looks like:
Given(/^I have \$(#{CAPTURE_CASH_AMOUNT}) dollars in my account/) do |amount|
  #step logic
end

This makes the meaning of the capture group very obvious and it also allows for refactoring of the regular expression to be a little simpler since it's done in one place: The transform method. For example if we wanted to include currency symbols:

CAPTURE_CASH_AMOUNT = Transform(/^(\$|€)(\d+)$) do |currency_symbol, digits|
end
Chris
Last edit
Chris
Posted by Chris to Chris's deck (2018-01-09 14:44)