The Issue
We use if/else Ruby statements when we need to do something different for when a condition is met than when it is not met. Usually it means that we do one thing when a string equals or contains a certain substring, and something else when it doesn’t. Lets take a look at how we can practically implement an if/else statement into our Watir Webdriver/Selenium script.
The Code
The first example is a simple if statement that will perform an action based on the login status of a Yahoo user. If the user is not logged in, it will enter the credentials and click the sign in button. If the user has logged in, it will sign out.
1 2 3 4 5 6 7 8 9 10 11 12 |
#ta101_if_statement.rb puts('if statement: logged in or not') <strong>if </strong>@browser.link(:id, 'uh-signin').present? @browser.link(:id, 'uh-signin').click @browser.input(:id, 'login-username').send_keys('my3qi@yahoo.com') @browser.button(:id, 'login-signin').click @browser.input(:id, 'login-passwd').send_keys(TA101ruby') @browser.button(:id, 'login-signin').click <strong>else </strong>@browser.button(:class, /uh-menu-btn/).click @browser.link(:id, 'uh-signout').click |
This is a fairly simple iteration. We can add complexity by using an additional if/else statement. This will perform an additional action (labelled ‘rinse and repeat’), which will check if the user is logged in again, and if they are, will put ‘logged in’ into the command line.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
puts puts('if statement: logged in or not') if @browser.link(:id, 'uh-signin').present? puts('not logged in') @browser.link(:id, 'uh-signin').click @browser.input(:id, 'login-username').send_keys('my3qi@yahoo.com') @browser.button(:id, 'login-signin').click @browser.input(:id, 'login-passwd').send_keys('TA101ruby') @browser.button(:id, 'login-signin').click else puts ('logged in') @browser.button(:class, /uh-menu-btn/).click @browser.link(:id, 'uh-signout').click end sleep(5) puts('rinse and repeat') if @browser.link(:id, 'uh-signin').present? puts('not logged in') @browser.link(:id, 'uh-signin').click @browser.input(:id, 'login-username').send_keys('my3qi@yahoo.com') @browser.button(:id, 'login-signin').click @browser.input(:id, 'login-passwd').send_keys('TA101ruby') @browser.button(:id, 'login-signin').click |
The Takeaway
Using the Ruby if/else logic in your test automation allows you to develop more complex and efficient scripts. Once you have a grasp of utilizing these statements in Watir Webdriver/Selenium, you can expand your test automation repertoire by incorporating the statements into your Cucumber step definitions.