Reputation: 1
How to find an element if it exists in multiple places in a page but has same id under same class? For example: There are two text fields with the same id and I would like to choose the 2nd one. It works when I just write the watir/ruby(without using page object) @b.text_fields(:id => 'color').last.set "red"
But I am unsuccessful so far to make it work using page object.
Thanks in advance
Upvotes: 0
Views: 638
Reputation: 46836
As mentioned in the comments, the best solution is to update the fields to have unique ids.
However, assuming that is not possible, you can solve the problem using an :index
locator. The following page object finds the 2nd color field, which is equivalent to Watir's @b.text_field(:id => 'color', :index => 1).set
:
class MyPage
include PageObject
text_field(:color_1, id: 'color', index: 0)
text_field(:color_2, id: 'color', index: 1)
end
Which would be called like:
page = MyPage.new(browser)
page.color_1 = 'red'
page.color_2 = 'blue'
If you are actually trying to the last field, ie replicate @b.text_fields(:id => 'color').last.set
, then the :index
would be "-1":
text_field(:color_2, id: 'color', index: -1)
Note that similar can be done when locating the fields dynamically within a method (as opposed to defined by an accessor):
class MyPage
include PageObject
def set_colors(color_1, color_2)
text_field_element(id: 'color', index: 0).value = color_1
text_field_element(id: 'color', index: 1).value = color_2
end
end
Upvotes: 1
Reputation: 11
@b.text_fields(:id=>'color',:index=>1).set "red"
This can solve your problem.
Upvotes: 0