如何编写单个黄瓜步骤定义,其中多个参数是可选的?

时间:2015-07-23 12:15:00

标签: cucumber

参考之前的问题/答案 In a method that take multiple optional parameters, how can any but the first be specified?

def foo(fruit=nil,cut=nil,topping=nil)
  fruit    ||= 'apple'
  cut      ||= 'sliced'
  topping  ||= 'ice cream'
  # some logic here
end

foo(nil,nil,'hot fudge')

如何将此示例包装到单个黄瓜步骤定义中,其中多个参数也是可选的,即我可以将任意数量的参数传递到步骤中?

喜欢这些,

I enter cut 'sliced' and topping 'Ice cream'. 
I enter fruit 'apple and topping 'Ice cream'.
I enter cut 'sliced'

我想复制用户只提供某些值,因为页面在字段中已经有默认值。

由于

2 个答案:

答案 0 :(得分:0)

你需要正则表达式。如果你写这个步骤很自然,那么你可以运行它,黄瓜会告诉你你需要什么。

➜  Fruit git:(master) ✗ cucumber
Feature: Toppings

  Scenario: Add fruit # features/test.feature:3
    When I enter cut "sliced" and topping "Ice cream" # features/test.feature:4

1 scenario (1 undefined)
1 step (1 undefined)
0m0.001s

You can implement step definitions for undefined steps with these snippets:

When(/^I enter cut "(.*?)" and topping "(.*?)"$/) do |arg1, arg2|
  pending # express the regexp above with the code you wish you had
end

并使用双引号。这有帮助。

答案 1 :(得分:0)

如果您想设置上述方法中的默认值:

Then (/^I enter (cut|fruit) '(.*?)'( and topping '(.*?)')?$/) do |action, param1, topping, param2|
  if param1.strip.empty?
    param1 = (action == 'cut' ? 'sliced' : 'apple')
  end
  print "I #{action} #{param1}"
  if topping
    param2 = 'ice cream' if param2.strip.empty?
    print " and topping #{param2}"
  end
  print "\n"
  # some logic here
end

否则:

Then (/^I enter (cut|fruit) '(.*?)'( and topping '(.*?)')?$/) do |action, param1, topping, param2|
  print "I #{action} #{param1}"
  if topping
    print " and topping #{param2}"
  end
  print "\n"
  # some logic here
end