Using proper grammar in Gherkin

2019-07-30 02:16发布

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?

2条回答
爷的心禁止访问
2楼-- · 2019-07-30 02:57

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).

查看更多
劳资没心,怎么记你
3楼-- · 2019-07-30 03:14

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)?$/
查看更多
登录 后发表回答