VOOZH about

URL: https://cucumber.io/docs/cucumber/step-definitions/

⇱ Step definitions | Cucumber


Skip to main content

A Step Definition is a method with an expression that links it to one or more Gherkin steps. When Cucumber executes a Gherkin step in a scenario, it will look for a matching step definition to execute.

To illustrate how this works, look at the following Gherkin Scenario:

Scenario: Some cukes
GivenI have 48 cukes in my belly

The I have 48 cukes in my belly part of the step (the text following the Given keyword) will match the following step definition:

  • Java
  • Kotlin
  • Scala
  • Ruby
  • JavaScript
packagecom.example;
importio.cucumber.java.en.Given;

publicclassStepDefinitions{
@Given("I have {int} cukes in my belly")
publicvoidi_have_n_cukes_in_my_belly(int cukes){
System.out.format("Cukes: %n\n", cukes);
}
}

Or, using Java8 lambdas:

packagecom.example;
importio.cucumber.java8.En;

publicclassStepDefinitionsimplementsEn{
publicStepDefinitions(){
Given("I have {int} cukes in my belly",(Integer cukes)->{
System.out.format("Cukes: %n\n", cukes);
});
}
}
package com.example
import io.cucumber.java8.En

class StepDefinitions : En {

init{
Given("I have {int} cukes in my belly"){ cukes: Int ->
println("Cukes: $cukes")
}
}

}
packagecom.example
importio.cucumber.scala.{ScalaDsl, EN}

class StepDefinitions extends ScalaDsl with EN {

Given("I have {int} cukes in my belly"){ cukes:Int=>
println(s"Cukes: $cukes")
}

}
Given('I have {int} cukes in my belly')do|cukes|
puts "Cukes: #{cukes}"
end
const{Given}=require('cucumber')

Given('I have {int} cukes in my belly',function(cukes){
console.log(`Cukes: ${cukes}`)
});

Expressions

A step definition's expression can either be a Regular Expression or a Cucumber Expression. The examples in this section use Cucumber Expressions. If you prefer to use Regular Expressions, each capture group from the match will be passed as arguments to the step definition's method.

  • Java
  • Kotlin
  • Scala
  • Ruby
  • JavaScript
@Given("I have {int} cukes in my belly")
publicvoidi_have_n_cukes_in_my_belly(int cukes){
}
Given("I have {int} cukes in my belly"){ cukes: Int ->
println("Cukes: $cukes")
}
Given("I have {int} cukes in my belly"){ cukes:Int=>
println(s"Cukes: $cukes")
}
Given(/I have {int} cukes in my belly/)do|cukes|
end
Given(/I have {int} cukes in my belly/,function(cukes){
});

If the capture group expression is identical to one of the registered parameter types's regexp, the captured string will be transformed before it is passed to the step definition's method. In the example above, the cukes argument will be an integer, because the built-in int parameter type's regexp is \d+ .