2
votes

I want to perform following steps:

  1. Type some element (variable name - 'username') in the input area
  2. Dropdown suggestions open up. [declaration : username = "user2"]
  3. Check if element 'username' is present in dropdown; if yes, then want to click on that element and done.

    <span class="main-dropdown">
      <div class="tt">
        <span class="all-suggestions">
          <div class="suggestion">
            <p>user1</p>
          </div>
          <div class="suggestion">
            <p>user2</p>
          </div>
          <div class="suggestion">
            <p>user3</p>
          </div>
        </span>
      </div>
    </span>
    

I have tried following :

  • @browser.div(:class,"suggestion").p(:text,username).wait_while_present @browser.div(:class,"suggestion").p(:text,username).click
  • @browser.span(:class,"all-suggestions").div(:class,"suggestion").p(:text,username).wait_while_present @browser.span(:class,"all-suggestions").div(:class,"suggestion").p(:text,username).click
  • @browser.span(:class,"main-dropdown").div(:class,"suggestion").p(:text,username).wait_while_present @browser.span(:class,"main-dropdown").div(:class,"suggestion").p(:text,username).click

Issue: 'user2' shows up in dropdown list but it is unable to click on that element from dropdown.

Any help would be appreciated.

1

1 Answers

4
votes

The problem is that the path to the element is over-specified. Watir handles each element method individually, returning the first match of each call. It does not account for chained methods.

For example, consider the first code that does not work:

@browser.div(:class,"suggestion").p(:text,username).click

Actually says:

  1. Find the first div on the page with class "suggestion".
  2. Within that div, find the first p with text username.

This means that Watir will only find the "user1" paragraph.

When nesting element calls, you only want to include elements that are the same ancestor for all elements. For example, any of the following would work:

# Using the only matching div.suggestion
@browser.div(:class => 'suggestion', :text => username).p.click

# Only using the common ancestor span.all-suggestions
@browser.span(:class,"all-suggestions").p(:text,username).click

If you really want to keep all of the nesting, you will need to use XPath:

@browser.p(:xpath => "//div[@class='suggestion']/p[text()='#{username}']").click