Last Updated: February 25, 2016
·
5.285K
· zedtux

Cucumber, Capybara 2.0 and Capybara::Ambiguous

This evening I have upgraded the gems of a private project after having executed all my tests to ensure that the gem upgrade didn't broke my code.

In the list of upgraded gem there was the new version of Capybara gem (https://github.com/jnicklas/capybara).

Executing again my tests thrown many times the following error:

Ambiguous match, found 2 elements matching field "Password" (Capybara::Ambiguous)

Having a look at the Capybara 2.0 Upgrade Guide written by Jo Liss (http://techblog.fundinggates.com/blog/2012/08/capybara-2-0-upgrade-guide/) make me understanding what is going wrong:

Capybara is now strict on the match of elements. If you want to fill in a field "Password" and a filed "Password confirmation", then you will have this error as the word Password could be found twice.

The solution provided in the Upgrade guide is not fine to me, because then the Cucumber scenario is less readable as we should use field id.

To fix this, just update the web_steps.rb file and change the step to fill in fields like the following:

When /^(?:|I )fill in "([^"]*)" with "([^"]*)"$/ do |field, value|
  # First try with a label
  xpath = "//label[normalize-space(translate(.,'*',''))='#{field}' or @for='#{field}']/.."
  if page.all(xpath).empty?
    # Then try with a input field
    xpath = "//input[@type='text' and (@id='#{field}' or @name='#{field}')]/.."
  end

  within(xpath) do
    fill_in(field, with: value)
  end
end

See a complete version in this gist I created.