{{ !articles[0].partner.isSponsoringArticle ? "Platinum" : "Portal" }} Partner

Writing Cucumber Step Definitions in JavaScript

Cucumber is a Behavior-Driven Development tool that lets developers describe their software's behavior in plain text using a business-readable DSL (Domain-Specific Language).  Project developers have added a useful adapter for Cucumber which allows users to write step definitions in JavaScript instead of Ruby (described in Joseph Wilk's blog).  To use Cucumber, you previously needed to know a slight amount of Ruby, now you can completely forgo using Ruby if you know a little JavaScript.  Cucumber supports testing for Java, Ruby, .Net, Flex, Python, web languages, and more.  

Here are the home page's seven steps for using Cucumber:

  • Describe behaviour in plain text
  • Write a step definition in Ruby (Now you can do this in pure JS!)
  • Run and watch it fail
  • Write code to make the step pass
  • Run again and see the step pass
  • Repeat 2-5 until green like a cuke
  • Repeat 1-6 until the money runs out

The new adapter in Cucumber is able to provide JS support for step definitions through TheRubyRacer.  This tool allowed Cucumber developers to build the JS adapter by embedding Google's V8 JavaScript interpreter into Ruby.

Here is an example of the feature:
Feature: Fibonacci
In order to calculate super fast fibonacci series
As a Javascriptist
I want to use Javascript for that

Scenario Outline: Series
When I ask Javascript to calculate fibonacci up to <n>
Then it should give me <series>

| n | series |
| 1 | [] |
| 2 | [1, 1] |
| 3 | [1, 1, 2] |
| 4 | [1, 1, 2, 3] |
| 6 | [1, 1, 2, 3, 5] |
| 9 | [1, 1, 2, 3, 5, 8] |
| 100 | [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] |
And the step definitions in JS:
Before(['@fibonacci'], function(){
fibResult = 0;

When(/^I ask Javascript to calculate fibonacci up to (\d+)$/, function(n){
assertEqual(0, fibResult)
fibResult = fibonacciSeries(n);

Then(/^it should give me (\[.*\])$/, function(expectedResult){
assertEqual(expectedResult, fibResult)

Cucumber developers have tried to make the JS API and the Ruby API as similar as possible, but the JS API currently doesn't have support for calling step definitions within step definitions with multi-line arguments.  It also doesn't support line reporting on step definitions.

The JS API also has a different way for loading code into the 'World' to make sure it is in scope within the step definitions.  For this kind of folder structure:


There would be this code within the features/support/env.js setup file:
//Cucumber resolves the files relative to the folder that contains the features folder.
Code inside the code_lives_here.js file would be available in the step definitions.
{{ tag }}, {{tag}},

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks