Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Watir, Page-objects: how to get all elements that have the same identifier

I have the following code code on my page I wanna check:

...    
<p class="tags-link"> 
<a href="/search?q=test1" rel="nofollow">test1</a>
<a href="/search?q=test2" rel="nofollow">test2</a> 
<a href="/search?q=test3" rel="nofollow">test3</a>
</p>
....
<p class="tags-link"> 
<a href="/search?q=test4" rel="nofollow">test4</a>
<a href="/search?q=test5" rel="nofollow">test5</a> 
<a href="/search?q=test6" rel="nofollow">test6</a>
</p>

....

I use Watir-webdriver and page-object. And I need to get all links related to blocks with "tags-link" class.

I have the following code:

element(:tags, :p, :css => "tags-link a")

tags_element returns the 1st link only.

The following code will give me just 3 links related to the 1st block:

element(:tags, :p, :css => "tags-link")
tags_element.element.links.each do |elm|
  puts elm
end

But I need to get all tags blocks

Now I have the following code that works, but I wanna be "page-object" oriented :

@browser.elements(:css =>".tags-link a").each do |tag|
  puts tag
end

Could you please help me...to get all links on the page related to "tags-link" using page-objects

Thanks, Anna

like image 684
Annet Avatar asked Jun 24 '13 13:06

Annet


2 Answers

You can define a collection of links in your page object using links:

class MyPage
    include PageObject

    links(:tag_link, :css =>".tags-link a")
end

This will create a collection_name_elements method that returns an array of matching page-object elements. You can iterate over it to perform an action on each element. For example, to output the text of each link:

page.tag_link_elements.each do |link|
    puts link.text
end
#=> test1
#=> test2
#=> test3
#=> test4
#=> test5
#=> test6
like image 90
Justin Ko Avatar answered Oct 05 '22 11:10

Justin Ko


This is all you need to do:

ary_of_tests = @browser.ps(:class, 'tag-links').map do |t|
    t.as.map do |x| 
        x.text 
    end 
end
=> [["test1", "test2", "test3"], ["test4", "test5", "test6"]]

If you do not like dynamic arrays you can always use the flatten method to make it one dimensional or to_s method to make it into a string. Defining a new class and specifying scenarios seems like overkill to me, but to each his own.

Note: ps(:class, 'tag-links) is a collection of all p elements with attribute class and value tag-links in the DOM of a given page.

like image 26
alp2012 Avatar answered Oct 05 '22 12:10

alp2012