The Issue
When there are more than two choices for an if statement, consider using a ‘case’ statement in Ruby. Case statements are designed to make handling of multiple conditions easier to code and easier to maintain than a long series of ‘elsif’ clauses. Lets take a look at how we can improve our Watir Webdriver/Selenium Scripts with case statements.
The Code
We’ll pass an argument when running the script and use a case statement to decide which browser to open. In the below code, we have defined “GC” as our browser, which, thanks to our case statement, will cause Chrome to open:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
ta101_case.rb browser = "GC" case browser when /IE/i, /internet.explorer/i @browser = Watir::Browser.new :internet_explorer when /GC/i, /chrome/i, /C/i @browser = Watir::Browser.new :chrome when /FF/i, /firefox/i Selenium::WebDriver::Firefox::Binary.path = 'C:/Program Files/Mozilla Firefox/firefox.exe' @browser = Watir::Browser.new :firefox else fail("Browser '#{browser}' is not recognized") end @browser.goto('www.yahoo.com') target = 'Arrest' puts puts("Case: Does the story list on #{browser}' contain '#{target}'?") stream = @browser.ul(:id, 'Stream') if stream.text.include?(target) puts("Found '#{target}'") else puts("No '#{target}' at the moment") end @browser.close |
After opening our defined browser, the script will search for a target variable. Again, we set the variable to be “GC”. According to our case statement, when the variable is set to GC,C, or chrome, the command to open a new Chrome Browser will be called. We have parameterized this using regular expression; by adding the i after our text within the slashes, we signify that the defined variable does not need to be case sensitive.
The Takeaway
Much like our if/else Ruby statements, case statements allow you to add additional logic and complexity to your Watir Webdriver/Selenium test 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.