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:

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.