黄瓜中的可选参数

时间:2013-08-20 23:07:40

标签: cucumber

我有一个步骤定义,我想要一个可选参数。我相信这个步骤的两个调用的例子比我所追求的更好地解释了。

I check the favorite color count
I check the favorite color count for email address 'john@anywhere.com'

首先,我想使用默认的电子邮件地址。

定义此步骤的好方法是什么?我不是正则表达的大师。我试过这样做但黄瓜给了我一个关于regexp参数不匹配的错误:

Then(/^I check the favorite color count (for email address "([^"]*))*"$/) do  |email = "default_email@somewhere.com"|  

2 个答案:

答案 0 :(得分:31)

optional.feature:

Feature: Optional parameter

  Scenario: Use optional parameter
    When I check the favorite color count
    When I check the favorite color count for email address 'john@anywhere.com'

optional_steps.rb

When /^I check the favorite color count(?: for email address (.*))?$/ do |email|
  email ||= "default@domain.com"
  puts 'using ' + email
end

输出

Feature: Optional parameter

  Scenario: Use optional parameter
    When I check the favorite color count
      using default@domain.com
    When I check the favorite color count for email address 'john@anywhere.com'
      using 'john@anywhere.com'

1 scenario (1 passed)
2 steps (2 passed)
0m0.047s

答案 1 :(得分:0)

@larryq,你比你想象的更接近解决方案......

optional.feature:

Feature: optional parameter

Scenario: Parameter is not given
    Given xyz
    When I check the favorite color count
    Then foo

Scenario: Parameter is given
    Given xyz
    When I check the favorite color count for email address 'john@anywhere.com'
    Then foo

optional_steps.rb

When /^I check the favorite color count( for email address \'(.*)\'|)$/ do |_, email|
    puts "using '#{email}'"
end

Given /^xyz$/ do
end

Then /^foo$/ do
end

输出:

Feature: optional parameter

Scenario: Parameter is not given
    Given xyz
    When I check the favorite color count
        using ''
    Then foo

Scenario: Parameter is given
    Given xyz                                                                   
    When I check the favorite color count for email address 'john@anywhere.com'
        using 'john@anywhere.com'
    Then foo                                                                    

2 scenarios (2 passed)
6 steps (6 passed)
0m9.733s