Watir. How to make a call to an element of page object, inside a line like $browser.link.click?

StackOverflow https://stackoverflow.com/questions/23661281

  •  22-07-2023
  •  | 
  •  

Question

We have a page objects elements like

 link           (:test_link,      xpath: './/a[@id = '3'])

 unordered_list (:list,              id: 'test')

And the code:

def method(elementcontainer, elementlink)

elementcontainer = elementcontainer.downcase.gsub(' ', '_')
elementlink = elementlink.downcase.gsub(' ', '_')
object = send("#{elementcontainer}_element")
object2 = send("#{elementlink}_element")


total_results_1 = object.element.links(id: '3')]").length
total_results_2 = object.element.links(object2).length
end

The last 2 lines contain the mystery.

The total_results_1 is able to get the number of links contained in the unordered list that have id = '3'.

total_results_2 does not work (of course). I don´t want to write in the middle of the code, again, the identification of the links. That is done in the page object.

How it is possible to write something like the total_results_2 line, but in a working version?

Was it helpful?

Solution

I might be misunderstanding the question, but I do not believe you need to create a method for what you want. It can all be done using the page object accessors.

Say we have the following page (I matched this to your accessors, though it seems unlikely that all links would have the same id):

<html>
  <body>
    <a id="3" href="#">1</a>
    <ul id="test">
      <li><a id="3" href="#">2</a></li>
      <li><a id="3" href="#">3</a></li>
      <li><a id="3" href="#">4</a></li>
    </ul>
    <a id="3" href="#">5</a>
  </body>
</html>

As you did, you could define the list with the accessor:

unordered_list(:list, id: 'test')

To get the links with id 3, but are only within the list, you could:

  1. Define the links as a collection - ie use links instead of link.
  2. Use a block to locate the elements. This would allow you to consider the element nesting - ie locate links within the list element.

This would be done with:

links(:test_link){ list_element.link_elements(:id => '3') }

All together, your page object would be:

class MyPage
  include PageObject

  unordered_list(:list, id: 'test')
  links(:test_link){ list_element.link_elements(:id => '3') }
end

To find the number of links, you would access the element collection and check its length.

browser = Watir::Browser.new
browser.goto('your_test_page.htm')

page = MyPage.new(browser)
puts page.test_link_elements.length
#=> 3
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top