Provide a description that matches steps in feature files and the implementation function that will be run.
Usage
given(description, implementation)
when(description, implementation)
then(description, implementation)
Arguments
- description
A description of the step.
Cucumber executes each step in a scenario one at a time, in the sequence you’ve written them in. When Cucumber tries to execute a step, it looks for a matching step definition to execute.
Keywords are not taken into account when looking for a step definition. This means you cannot have a
Given
,When
,Then
,And
orBut
step with the same text as another step.Cucumber considers the following steps duplicates:
This might seem like a limitation, but it forces you to come up with a less ambiguous, more clear domain language:
To pass arguments, description can contain placeholders in curly braces.
To match:
use:
If no step definition is found an error will be thrown.
If multiple steps definitions for a single step are found an error will be thrown.
- implementation
A function that will be run during test execution.
The implementation function must always have the last parameter named
context
. It holds the environment where test state can be stored to be passed to the next step.If a step has a description
"I have {int} cucumbers in my basket"
then the implementation function should befunction(n, context)
. The{int}
value will be passed ton
, this parameter can have any name.If a table or a docstring is defined for a step, it will be passed as an argument after plceholder parameters and before
context
. The function should be afunction(n, table, context)
. See an example on how to write implementation that uses tables or docstrings.
Details
Placeholders in expressions are replaced with regular expressions that match values in the feature file. Regular expressions are generated during runtime based on defined parameter types.
The expression "I have {int} cucumbers in my basket"
will be converted to
"I have [+-]?(?<![.])[:digit:]+(?![.]) cucumbers in my basket"
. The extracted value of {int}
will be passed to the implementation function after being transformed with as.integer
.
To define your own parameter types use define_parameter_type
.
Examples
given("I have {int} cucumbers in my basket", function(n_cucumbers, context) {
context$n_cucumbers <- n_cucumbers
})
given("I have {int} cucumbers in my basket and a table", function(n_cucumbers, table, context) {
context$n_cucumbers <- n_cucumbers
context$table <- table
})
when("I eat {int} cucumbers", function(n_cucumbers, context) {
context$n_cucumbers <- context$n_cucumbers - n_cucumbers
})
then("I should have {int} cucumbers in my basket", function(n_cucumbers, context) {
expect_equal(context$n_cucumbers, n_cucumbers)
})