Jitu
Jitu

Reputation: 635

Handle cucumber ambiguous steps

I am new to cucumber and I would like to ask for a suggestion for how I can organize the following step definition,

Feature: Manage events
  In order to Manage events
  Organizer
  wants to create new events

  Background:
    Given I am logged in as organizer

  Scenario: Publish new event
    Given I am on the new event page
    When I fill in "Title" with "Rails event"
    And I fill in "Start at" with "2012-5-4"
    And I fill in "End at" with "2012-5-5"
    And I fill in "Description" with "Bla bla"
    And I check "Published"
    And I press "Create Event"
    Then I should see "Rails event"

Here are the step definitions that create the ambiguity,

    When /^I fill in "Start at" with "(.*?)-(.*?)-(.*?)"$/ do |year, month, day|
      enter_date(:event_start_at, year, month, day)
    end

    When /^I fill in "End at" with "(.*?)-(.*?)-(.*?)"$/ do |year, month, day|
      enter_date(:event_end_at, year, month, day)
    end

    When /^I fill in "(.*?)" with "(.*?)"$/ do |name, value|
      fill_in name, :with => value
    end

    private
    def enter_date(id, year, month, day)
        select year, :with => "#{id}_1i"
        select month, :with => "#{id}_2i"
        select day, :with => "#{id}_3i"
    end

What happens is that the first 2 definition is ambiguous with the last definition. But for start and end date, I have to handle them differently. What I know is that cucumber has the --guess option which solves that issue. But is this the best practice?

Upvotes: 1

Views: 359

Answers (2)

Doug Noel
Doug Noel

Reputation: 704

Get rid of the quotes around "Start at" and "End at". They will no longer match your last step. I've found that quotes cause a lot of ambiguity, and so I generally only use them for things like filenames or paths that have spaces in them. When in doubt, I find that removing quotes is the best practice as it removes a lot of guesswork for Cucumber.

Upvotes: 0

dj2
dj2

Reputation: 9620

Why not just do something like:

When /^I fill in "([^"]*)" with "([^"]*)"$/ do |name, value|
  case(name)
  when "Start at" then
    parts = value.split(/-/)
    enter_date(:event_start_at, parts[0], parts[1], parts[2])
  when "End at" then
    parts = value.split(/-/)
    enter_date(:event_end_at, parts[0], parts[1], parts[2])
  else
    file_in name, :with => value
  end
end

(Or, something along those lines, typed into the textbox so not sure if that will run correctly as is.)

Upvotes: 2

Related Questions