ruby cucumber 如何使用黄瓜表达式让不同的步骤调用相同的定义

问题描述 投票:0回答:1

说我想要

Given something
When the sky is blue
And grass is green
Then I'm happy

但我想要

When('the sky is blue') do
puts 'good'
end

When('grass is green') do
puts 'good'
end

完全相同的步骤定义,类似

When(('the sky is blue')('grass is green')) do
puts 'good'
end

要使其工作,语法必须是什么 - 使用 ruby-cucumber 和 cucumber 表达式而不是正则表达式?请帮忙

ruby cucumber expression definition
1个回答
0
投票

您也许可以使用 Cucumber 表达式 来做到这一点,但是当人们提供奇怪的输入时,很难假设不会出现过度匹配或不足匹配的边缘情况。例如,您可能期望以下内容有效:

( the )sky/grass is blue/green

与您的示例匹配,但它也会与当草是蓝色而天空是绿色之类的文本意外匹配。这可能不是您想要的。如果您无法概括,那么您可能需要使用具有更明确锚定的正则表达式,或者考虑拆分您的 Gherkin 以避免连接步骤

Gherkin 允许您使用多种方式提取令牌进行处理。假设您没有其他类似的步骤会导致混乱,即使无需在 Cucumber 配置中创建 自定义参数类型,以下操作也应该有效。其他方法也可以工作,具体取决于您的需求。

# Gherkin
When the "sky" is "blue"
And "grass" is "green"
Then I am "happy"

# flexible object/color step with cucumber
# expressions and a case statement
When("(the ){word} is {word}") do |obj, color|
  case
  when (obj == "sky" and color == "blue") && 
       (obj == "grass" and color == "green")
    @emotional_state = "happy"
  else
    @emotional_state = "unhappy"
  end
end 

# use state from the previous step to measure
# your happiness quotient
Then("I am {word}") do |emotional_state|
  @emotional_state == emotional_state
end

您还可以考虑制作场景大纲或传递数据表,以便您可以更轻松地绘制关于什么让您快乐的真值表。根据您的目标以及将步骤过度简化到步骤不够清晰的可能性,这至少应该让您朝着正确的方向前进。

© www.soinside.com 2019 - 2024. All rights reserved.