Search code examples
arraysrubywatirwatir-webdriverpage-object-gem

Can't access text of an element in an array using PageObject and Watir


I have an array that I collected:

array= @browser.ul(:class => 'parent').links

I am then trying to access the text on a specific element in the array iterating over the array like this:

array.each_with_index do |i, index|

If I do something like:

array[index]

I get back the anchor element object. And if I do:

array[index].element

I will get back an HTML element object. But if I try to get anything element specific such as:

array[index].text
array[index].value

then I get an "unable to locate element" error.

I am using Watir, Page Object, and Ruby.

Here is the scope of the entire array iteration, it's fairly simple:

array= @browser.ul(:class => 'parent').links
array.each_with_index do |i, index|
  if index == array.length-1
    sleep 1
    @browser.button(:text => 'Complete').when_present.click
  else
    sleep 1
    @browser.button(:text => 'Complete').when_present.click
    @browser.a(:text => 'Next').when_present.click
  end
end

I am trying to add an elsif that checks for the text of a link, so that if it's on that particular page/link it does something specific while on that page.

For example, in pseudo-code:

If array element text = "Instructions", then dont click the complete button, just click next.

I suppose I would be open to solving this in any way that lets me identify the link it is currently on, so that I can perform a set action, but I figured grabbing the text of the current link would be easiest, hence the question.

How can I access the text or specific attributes of an element in this array?


Solution

  • Most probably the DOMs of your elements are changing after some interaction (like clicking 'Complete' button).

    My suggestion is to find all the elements once again after each interaction.

    Try something like that:

    array = @browser.ul(:class => 'parent').links
    index = 0
    array.length.times do
      sleep 1
      if index == array.length-1
        @browser.button(:text => 'Complete').when_present.click
        array = @browser.ul(:class => 'parent').links #We are finding new array after possible change
      elsif  array[index].text == 'Instructions'
        @browser.a(:text => 'Next').when_present.click
      else
        @browser.button(:text => 'Complete').when_present.click
        @browser.a(:text => 'Next').when_present.click
      end
      array = @browser.ul(:class => 'parent').links #And once again
      index = index+1
    end
    

    Attention: I can not guarantee that the code above will work because I've got no page to test it on to be sure. If it is not working - try to modify it using the idea