1
votes

I'm pretty new to Watir.

I was looking for a way to detect the type of object received by a subroutine, in order to apply the correct method. The final result should be something like:

sub clickOnElement (elementId, elementRef)
element= browser.(elementId.to_sym, elementRef)
case TypeOfElement (element)
   :link            element.click
   :radio           element.set
   :checkbox        element.set
   :list            ....
end
end

My question is about the actual implementation of TypeOfElement().

Any suggestion or pointer is appreciated: thank you in advance

Sergio

1
Just out of curiosity, why do you need to do this? Usually you know what type of element you are working with so can directly call the applicable methods. - Justin Ko

1 Answers

3
votes

You can do the case statement based on the class of the element variable (after converting it to its subtype). This way you do not have to implement your own TypeOfElement method.

Something like:

e = browser.element
case e.to_subtype
    when Watir::CheckBox
        e.set
    when Watir::Anchor #Link
        e.click
    else
        raise( e.class.to_s + ' not handled' )
end

Note:

  • browser.element returns the first element, which will be the HTML tag. Therefore, in the above case statement will raise an exception. I assume e will be something more specific.
  • At the start of the case statement it is just 'e.to_subtype' instead of 'e.to_subtype.class' (as explained in How to catch Errno::ECONNRESET class in "case when"?).