How to find the data-id in watir?
Asked Answered
S

1

6

I am new to watir testing. Would somebody help me to find the following element.

<div class="location_picker_type_level" data-loc-type="1">
  <table></table>
</div>

I like to find this div, data-loc-type with table exists.

ex:

browser.elements(:xpath,"//div[@class='location_picker_type_section[data-loc-type='1']' table ]").exists?
Samuella answered 22/3, 2013 at 13:1 Comment(0)
S
13

Watir supports using data- type attributes as locators (ie no need to use xpath). Simply replace the dashes with underscores and add a colon to the start.

You can get the div using the following (note the format of the locator for the attribute: data-loc-type -> :data_loc_type ):

browser.div(:class => 'location_picker_type_level', :data_loc_type => '1')

If it is only expected that there is one div of this type, you can check that it has a table by doing:

div = browser.div(:class => 'location_picker_type_level', :data_loc_type => '1')
puts div.table.exists?
#=> true

If there are multiple divs that match and you want to check that at least one of them has the table, use the any? method for a divs collection:

#Get a collection of all div tags matching the criteria
divs = browser.divs(:class => 'location_picker_type_level', :data_loc_type => '1')

#Check if the table exists in any of the divs
puts divs.any?{ |d| d.table.exists? }
#=> true

#Or if you want to get the div that contains the table, use 'find'
div = divs.find{ |d| d.table.exists? }
Skylab answered 22/3, 2013 at 14:24 Comment(5)
Thank you very much not only for the answer.. You explained me very well. I really appreciate you. You are the man... !Samuella
One more doubt. Its like a accordion. It should return true only its expanded. is it any way to find this thing?Samuella
Short answer is yes. How would depend on the implementation. If the table is only displayed when expanded, then you should change the table.exists? to table.present? (which checks that the table exists in the html and is visible to the user).Skylab
When did we add the support for :data_xxx selection specifiers? that's awesome, I thought we had to monkeypatch that in.. (off to modify my code)Raimes
@ChuckvanderLinden, watir-classic had it added in (version 3)[watir.com/2012/04/24/watir-3-released/]. For watir-webdriver it looks to be about the same time.Skylab

© 2022 - 2024 — McMap. All rights reserved.