Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using proper grammar in Gherkin

It seems to be very difficult to look up documentation about Gherkin, so I was wondering if there was a way to augment step definitions to enable the tester to use proper grammar. One example that shows what I mean is:

...Testing...
Then I see there is 1 item
...More testing...
Then I see there are 2 items

Obviously, these two steps would use the same code. I defined a step definition like this which almost works:

Then(/^I see there (is|are) (\d+) item(s)?$/) do |item_count|
  ...code...
end

Except the problem is that it interprets is/are and the optional plural s as arguments. Is there any way to signal to Gherkin that these are just for allowing proper grammar?

like image 308
Chase Sandmann Avatar asked Sep 01 '25 22:09

Chase Sandmann


2 Answers

Use ?: at the start of the group marks it as noncapturing, Cucumber won’t pass it as an argument.

/^I see there (?:is|are) (\d+) item(?:s)?$/
like image 163
Grasshopper Avatar answered Sep 05 '25 11:09

Grasshopper


These steps don't have to use the same code. Instead they can call the same code. If you apply this pattern you can then concentrate on your steps doing just the single thing they should be doing which is using well expressed natural language to fire code. So ...

module ItemStepHelper
  def see_items(count:)
    ...
end
World ItemStepHelper

Then 'I see there is one item' do
  see_items(count: 1)
end

Then 'I see there are \d+ items' do |count|
  see_items(count: count)
end

Now obviously with this example thats quite a bit more boilerplate for very little benefit, but when you apply the pattern on more realistic examples then the benefits really begin to kick in. In particular you never have to write a really complex regex for step definitions (in practice 90% or more of my step defs don't even use a regex).

like image 26
diabolist Avatar answered Sep 05 '25 09:09

diabolist