Sunday, November 30, 2014

Transforming a line item



Extending the World class is one way to extend the functionality of Cucumber. In this section we will
look at another. In a few of our step definitions we have specified that we wanted to use a specific
“line item”. In those steps we had to always take the String Cucumber passed and convert it to a
number using the to_i method. If we want Cucumber to automatically convert it for us we can use
a Transformation. Let’s look at that now.
                                        The first thing we need to do is create a new file in the support directory named transformations.rb. The file name doesn’t matter; I just like to collect all of my transformations in the same file. On a typically large project you might see up to five or six transformations. In this file we will create our first transformation:

  Transform /^line item (\d+)$/ do |line_string|
   line_string.to_i
  end


This structure should look familiar. It is very similar to step definitions except it begins with the
word Transform instead of Given, When, or Then. To break it down completely, what we are saying
with this code is find a capture group of a step definition (portion of a step definition surrounded by
parentheses) that contains “line item” plus a number and perform the following action on the value
of the number. In order for this Transformation to find the appropriate step definitions we will need
to move the opening parentheses to surround the entire match.

Then /^I should see "([^"]*)" as the name for (line item \d+)$/ do |name, lin\
e_item|

Now we no longer need to convert the line_item parameter to a number since the Transformation
takes care of this for us.

       This technique is very useful when you have values that need to be converted and you wish to move
the logic from multiple steps to one Transformation. For example, imagine you need to perform a
lot of date handling. It would be nice to say things like today, tomorrow, or yesterday and have a
Transformation object create a date object.

Source: Cucumber and Cheese book

No comments:

Post a Comment