Friday, April 9, 2010

Watir:Regular Expressions: What is Regular expression in ruby scripting?

Regular Expressions

Watir supports regular expressions in method calls.
Here is an example using the link method to click a link using the url attribute:
ie.link(:url, /shtml/).click
This will click the link that matches shtml.

How do I use regular expressions for object recognition?

Watir allows the tester to use Regular Expressions for object recognition instead of using the full string literal. This is useful for HTML objects that are dynamically created.
For example in my WebSphere application we may have a link with this URL
$ie.link(:url, "javascript:PC_7_0_G7_selectTerritory('0',%20'amend')").click
    
However this: 'PC_7_0_G7_' will change dependant on the environment.
With RegEx we could find that link by doing :
$ie.link(:url, /selectTerritory\('0',%20'amend'\)/).click
    
or this
$ie.link(:url, /javascript.*selectTerritory\('0',%20'amend'\)/).click
    
note: '.*' will match any character or digit any number of times.
RegEx contains special characters that need to be escaped. For example here ')' we use the backward slash to escape a closing bracket.
To find out what characters need to be escaped, go into irb, then enter
Regexp.escape "javascript:PC_7_0_G7_selectTerritory('0',%20'amend')"
    
the escape sequences will be returned
=> "javascript:PC_7_0_G7_selectTerritory\\('0',%20'amend'\\)"
    
note: use only one backslash; we are shown two, because they are escaped within a string,
aidy

No comments:

Post a Comment