2013-08-20 76 views
15

我有一個步驟定義,我希望有一個可選參數。我相信這個步驟的兩個呼叫的例子比任何其他事物都更好地解釋我所追求的。黃瓜可選參數

I check the favorite color count 
I check the favorite color count for email address '[email protected]' 

在第一個例子中,我想使用默認的電子郵件地址。

定義這一步的好方法是什麼?我不是正則表達式大師。我試圖這樣做,但黃瓜給了我一個錯誤關於正則表達式的參數不匹配:

Then(/^I check the favorite color count (for email address "([^"]*))*"$/) do |email = "[email protected]"| 
+1

這有什麼錯兩步定義? –

+0

本質上沒有。只是想拉伸我的黃瓜肌肉,看看有什麼可能。 – larryq

+0

兩個定義意味着大部分時間重複代碼,所以理論上條件從句更好。 – Smar

回答

27

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 '[email protected]' 

optional_steps.rb

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

輸出

Feature: Optional parameter 

    Scenario: Use optional parameter 
    When I check the favorite color count 
     using [email protected] 
    When I check the favorite color count for email address '[email protected]' 
     using '[email protected]' 

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

這很好,謝謝你,但我可以問一下'?:'位是幹什麼的? – larryq

+3

'?:'是一個[非捕獲組](http://www.regular-expressions.info/refadv.html)。 –

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 '[email protected]' 
    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 '[email protected]' 
     using '[email protected]' 
    Then foo                  

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