Tutorial 13 – Expressions in Cucumber BDD
What you will Learn :
Backgound
Cucumber Expressions
Capture group
Quantifiers in regular expressions
Backgound
Cucumber supports 2 types of expressions:
1) Cucumber Expressions and
2) Regular Expressions
Cucumber Expressions
There are certain rules for defining cucumber expressions:
Rule#1)
By default, the step definition file will generate ONLY cucumber expressions. To understand this rule, let us refer the below feature file
Below is the corresponding step definition for each step in the feature file.
If you notice below, the cucumber expressions {string} and {int} are automatically getting generated by default
Let us add one new step in our feature file
Save the file and run it.
The console shows us the missing implementation. Notice again that cucumber expressions {string} and {int} got generated by default
Rule#2)
We can also use regular expressions in step definition file. We cannot mix both expressions (cucumber and regular) in a single step definition method.
To understand this rule, let us replace cucumber expression {int} with regular expression (\\d+) in line number 14.
So, in the same method, we have a mix of cucumber expression {string} and regular expression (\\d+)
Save the file
Run the feature file
Note below. There is an exception in console. So we cannot have a mix of both the expressions in a method
Rule#3)
We can mix regular expressions and cucumber expressions in a step definition file. This means that, in one step definition method we can have cucumber expression and in another method we can have regular expression.
To understand this rule, see below. Use regular expressions for method in line 14 and use cucumber expression for method in line 19
Save the file
Run the feature file
Notice the console o/p below. There is no error this time
Capture group
The round brackets ( ) are capture groups and within them is the range of the group. So in the below method, the ranges are .* and d+
The dot matches any character, and the star allows the dot to be repeated any number of times, including zero.
\d is a digit (a character in the range 0-9), and + means 1 or more times. So, \d+ is 1 or more digits.
Quantifiers in regular expressions
Quantifier means how many times a character needs to be occurred. There are 4 types of quantifiers in regular expressions:
plus +
asterisk *
question mark ?
total number of occurences {n}
Below is the brief description/example of above 4 quantifiers:
([0-9]+)
This means the digits 0 to 9 can appear once or more than once
([0-9]*)
This means the digits 0 to 9 can appear zero or more
([0-9]?)
This means the digits 0 to 9 can appear zero or once
([0-9]{3})
This means, between 0-9, generate 3 digits, example: 000, 131, 610, 418,, etc
You can refer the website for further details and examples
https://www.regular-expressions.info/refrepeat.html
Thank you for reading!