【问题标题】:Is there any way to specify eg (car|cars) in a cucumber step definition?有没有办法在黄瓜步骤定义中指定例如 (car|cars) ?
【发布时间】:2020-03-19 14:10:56
【问题描述】:

所以我有两个场景....一个开始

Given I have 1 car

另一个开始

Given I have 2 cars

我希望他们使用相同的步骤定义 - 即类似这样的东西

 Given('I have {int} (car|cars)',

我知道可以指定 2 个可能的值(即汽车或汽车),但我终其一生都不记得怎么做的了。有人知道吗?我正在使用打字稿、量角器、角度、硒。

也试过

Given(/^I have {int} (car|cars)$

【问题讨论】:

    标签: cucumber cucumberjs


    【解决方案1】:

    在 cukeExp 中,() 成为可选字符。这就是你想要的。

    所以你的表达方式是

    Given('I have {int} car(s)')
    

    乐于提供帮助 - 更多信息可以在这里找到:https://cucumber.io/docs/cucumber/cucumber-expressions/ - 切换到顶部的 JS 代码。

    Luke - Cucumber 贡献者。

    【讨论】:

      【解决方案2】:

      Luke 的回答很棒,绝对是拉屎时的标准做法。

      我会(并且确实)采取不同的方法。我强烈认为,即使是像他使用的那样的单个表达式的复杂性也不值得重复步骤。让我解释和说明。

      这种方法背后的基本思想是每个步骤定义的内部必须是对辅助方法的一次调用。当您这样做时,您不再需要表达式或正则表达式。

      我更喜欢并在我的项目中使用

      module CarStepHelper
        def create_car(amount: 1)
          Lots of stuff to create cars
        end
      end
      World CarStepHelper
      
      Given 'I have one car' do
        create_car
      end
      
      Given 'I have two cars' do
        create_car(amount: 2)
      end
      

      Given('I have {int} car(s)')
       lots of stuff to create cars
      end
      

      因为

      • 步骤定义更简单(没有正则表达式,没有黄瓜表达式
      • 创建汽车的东西稍微简单一些(不处理正则表达式或表达式)
      • 辅助方法支持并鼓励更广泛的表达,例如
      Given Fred has a car
      Given there is a blue car and a red car
      
      • 辅助方法鼓励步骤之间更好的通信,因为您可以分配与步骤定义相关的结果,例如
      Given Fred has a car
       @freds_car = create_car
      end
      
      Given there are two cars
       [@car1, @car2] = create_car(amount: 2)
      end
      

      Cucumber 表达式和 Cucumbers 正则表达式非常强大且非常易于使用,但您无需使用它们就可以非常有效地 Cuke。步骤定义效率是一个神话,通常是一种反模式,如果您确保每个步骤 def 只是一个调用,您就不必再担心它,并且您将避免许多 cuker 陷入的错误,即编写过于复杂包含大量参数、正则表达式和|或表达式的步骤定义。

      【讨论】:

        【解决方案3】:

        据我所知,您的步骤定义应如下所示。

        Given(/^I have "([^"]*)?" (car|cars)*$/, (number, item) => {

        您仍然可以简化第一个正则表达式。

        干杯!

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-07-12
          • 1970-01-01
          • 2014-01-10
          • 1970-01-01
          相关资源
          最近更新 更多