Skip to content
This repository was archived by the owner on Nov 16, 2018. It is now read-only.

Step Argument Transforms

larrytheliquid edited this page Aug 13, 2010 · 28 revisions

Step argument transforms help your step definitions be more DRY. You can use the Transform method to register a regular expression along with a code block. Before captured regex groups get yielded as arguments to step definitions, an attempt is made to match them against any registered Transform. If there is a match, the return value of the block supplied with the transform is yielded as the step definition argument instead. Here is an example:

# support file
Transform /^user \w+$/ do |step_arg|
  User.find_by_username /(\w+)$/.match(step_arg)[0]
end

# step definition file
Then /^(user \w+) should be friends with (user \w+)$/ do |user, friend|
  user.should be_friends_with(friend)
end

# feature file
Scenario: friend'ing
  Given ...
  When ...
  Then user larrytheliquid should be friends with user dastels

Note that sometimes you may not need to parse the entire step_arg and may only care about a specific Regexp capture group being matched. For this more common case, you can use an optional syntax for Transform where the block supplied has arguments that correspond to capture groups in the registered regex:

# support file
Transform /^user (\w+)$/ do |username|
  User.find_by_username username
end

One key thing to remember is to provide some contextual data like “user” so you don’t end up transforming every single argument to a step definition. See this blog post for a more detailed explanation and examples.

Clone this wiki locally