Search code examples
rubywatirpage-object-gem

How to get an element list based on other element in a table using page-object?


How to get an element's text list based on the other element in a table using watir page-object I have used xpath to get it but is there a better approach as using xpath is not a problem but I need to writing a lot of xpaths for getting these list as elements may change based on tables.

For the below table am getting the element's text list as follows:

xpath for fuel: //table[contains(@id,'scheduleData')]/descendant::span[@id='label' and text()='F']/following::span[2]

xpath for inspection: //table[contains(@id,'scheduleData')]/descendant::span[@id='label' and text()='I']/preceding::span[1]

So for each Fuel and Inspection points which has data I need to find encrypted locations and I need to maintain Fuel and Inspection locations list separate.

This is a small example as I cannot post whole table as it is huge and data is sensitive.

table id: 'scheduleDataab12'
-----------------------------------------------------------
Fuel Point | Company | Location | Inspection Point | Time |
-----------------------------------------------------------
F | Google | XMAT | I | 20/12/2018 08:00
... | Apple | MBXZ | ... | 20/12/2018 08:00
K | Amazon | JKLD | O | 20/12/2018 08:00
... | Microsoft | VBAB | ... | 20/12/2018 08:00

I have posted the html content in the gist github page in the below link

In the below html this is the table class: ricGrid ricGridLoaded in this table there are two headers in the thead I need to remove the first tr and then convert whole table into hashes.

HTML Link:https://gist.github.com/anilreddy/ce55341b2337889f17e498393cff2d81


Solution

  • Simple Table

    For a simple table, I think the most readable approach is to use Watir's Table#hashes method to extract the text.

    You would define an accessor for the table:

    class MyPage
      include PageObject
    
      table(:schedule_data, id: /scheduleData/)
    end
    

    Then use #hashes to get an Array of Hashes that represent each row:

    data = page.table_element.hashes
    #=> [{"Fuel Point"=>"F", "Company"=>"Google", "Location"=>"XMAT", "Inspection Point"=>"I", "Time"=>"20/12/2018 08:00"}, {"Fuel Point"=>"...", "Company"=>"Apple", "Location"=>"MBXZ", "Inspection Point"=>"...", "Time"=>"20/12/2018 08:00"}]
    
    data.find { |r| r['Fuel Point'] == 'F' }.fetch('Company')
    #=> "Google"
    

    Table With Extra Header

    For the table with an extra header row, you will need to write your own method. The code would be similar to Table#hashes, but with an extra step to ignore the first row.

    data = your_table_element.strings
    data.shift # ignore first header
    header = data.shift
    data.map { |d| Hash[header.zip(d)] }
    #=> [{"FL"=>"F", "IN"=>"?", "Circ-7"=>"HM563", "City"=>"CHICO", "State"=>"TX", "ETA"=>"", "ETC"=>"05 20:59