Optional parameter in cucumber

larryq picture larryq · Aug 21, 2013 · Viewed 22.1k times · Source

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

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

Answer

basti1302 picture basti1302 · Aug 21, 2013

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

output

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