The Issue

We can use the Rescue  statements in Ruby to allow us to execute a set of actions, in the case that another set of actions fails (causing an exception). An exception is a special object that indicates that something has gone wrong. When this occurs, an exception is raised (or thrown), and, by default, Ruby programs terminate when an exception occurs. But it is possible to declare exception handlers (i.e. Rescue) that can prevent the termination.  This is especially useful in your Watir/Selenium WebDriver based Automation because it allows you to execute the bulk of a given Automation Test (Script) even if there is an exception (Failed Validation) earlier on in the script.

There are three statements utilized in a Rescue: Begin, Rescue and End. Lets take a look at how we can implement it in a Watir Webdriver script.

The Code

After we place the begin, we input our desired actions. In this case, we are checking if the text includes our the target variable we defined as ‘President’. We can then place rescue after. As we have put the fail statement if the target is found, the script will move from the fail, to the rescue. Within the rescue we have placed a puts statement, and a command to take a screenshot. After, we can place end to wrap everything up. Once we run the script, we can see the command line output as this:

The Takeaway

The rescue Ruby statements are used in a similar fashion to the if/else/then statements, mainly to circumvent an exception, and perform a different action in return. They expand your automation toolkit and give you a greater freedom of choice in how you build out your test scripts.