Optional parameter in cucumber

2019-02-08 02:48发布

I have a step definition in which I'd like to have an optional parameter. I believe an example of two calls to this step explains better than anything else what I'm after.

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

In the first instance, I would like to use a default email address.

What's a good way of defining this step? I'm no regexp guru. I tried doing this but cucumber gave me an error regarding regexp argument mismatches:

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

标签: cucumber
2条回答
神经病院院长
2楼-- · 2019-02-08 03:25

@larryq, you were closer to the solution than you thought...

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

output:

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
查看更多
ら.Afraid
3楼-- · 2019-02-08 03:45

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

output

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
查看更多
登录 后发表回答