Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to select the first element from a dropdown. RoR/Capybara/Selenium

So this code was working perfectly fine, until I recently updated my selenium webdriver:

When /^I search for (.*)$/ do |term|
    term = " " if term == "blank"
    step "I fill in search with #{term}"
    within(".navbar-search") do
        page.find(:css, "li:first").click
    end
end

I updated, and now I get the following error:

 An invalid or illegal string was specified (Selenium::WebDriver::Error::UnknownError)
  ./features/step_definitions/search_steps.rb:5:in `block (2 levels) in <top (required)>'
  ./features/step_definitions/search_steps.rb:4:in `/^I search for (.*)$/'
  features/search_friend.feature:13:in `When I search for <term>'

Here is the cucumber feature:

@javascript
Scenario Outline: The search bar
    Given I login
    And I have a contact named ABC
    And I have a contact named DEF
    And I have a contact named GHI
    When I search for <term>
    Then I should see the message <message>

    Examples:
    | term | message |
    | ... some examples ... | |
like image 438
wachichornia Avatar asked Dec 03 '22 23:12

wachichornia


1 Answers

I guess you updated not only Webdriver but also Capybara.

Capybara 2.1 now uses driver's implementation of CSS selectors. In case of Selenium Webdriver it means that browser's implementation is used. :first pseudo selector is not standard and isn't supported by browsers so your CSS selector is not valid.

Previously it worked because Capybara converted CSS selector to XPath using Nokogiri. Nokogiri supports :first pseudo selector.

So you should change your invalid CSS selector to something valid like:

  • page.first(:css, 'li').click
  • page.find(:css, 'li', match: :first).click (the difference between previous variant and this one is that this variant waits for element to appear on the page but the first one doesn't wait. See this section of Capybara README to get more information on match)
  • page.find(:css, "li:first-child").click
  • page.find('li:first-child').click
like image 116
Andrei Botalov Avatar answered Dec 21 '22 23:12

Andrei Botalov