‘Step’ into your cucumber feature

This post is about a way to reduce your inconvenience when writing step definitions in cucumber using Vim.

When I write my cucumber stories, I normally try to draft the step description on the ‘feature’ file:

Scenario: Login works
Given I have a valid page
Then the user enters "Neo" as username and 35 as age

The next step in this regard is to add a step definition:

Then(/^the user enters “([^”]*)” as username and (\d+) as age$/) do |arg1|
#step definiton here..
end

This involves a rather cumbersome step of either

  • copying and pasting the lines into the step definition file and then replacing the numbers and strings with their regex counterparts, manually
  • Running the feature as it is and then waiting for cucumber to show the pending test case suggestion:
You can implement step definitions for undefined steps with these snippets:
Then(/^the user enters “([^”]*)” as username and (\d+) as age$/) do |arg1, arg2|
pending
end

While the second option is a quick-win, it involves a context switch and a wait time until cucumber returns the error.

I was thinking about how to solve this and then arrived at the option of using Ultisnips. The snippet below does the job:

The way to use this snippet is easy:

  • Copy this snippet into one of your runtime paths , inside a directory called ‘Ultisnips’
  • Copy the step definition from the feature file
  • Paste it onto a step definition file (*_step.rb)
  • Visual Select the entire line using `vg_` or other mechanisms
  • Press tab to invoke Ultisnip completer(your key might vary depending upon your vim config)
  • Then type “step” for invoke this snippet
  • Then press “tab” and voila!
  • You have the step transformed into the regex counterparts.

The following recording shows the flow(though the keystrokes are not shown on the screen)

Result

This generates only one of the arguments for the step(arg1 in this case):

Then(/^the user enters “([^”]*)” as username and (\d+) as age$/) do |arg1|
end

As additional improvements, I would like to have the block arguments for the step definition populated automatically using the placeholders. But as of now, I am not able to do it as the placeholders , in this case, will be dynamic (depending upon the number of arguments in the step). So, as an example, I would like to have the step definition generated as :

I leave it to the readers and @SirVerI to suggest me a way to do this, if there is one.