The Issue

We previously detailed how to use Rescues in Ruby for Watir Webdriver scripts. Now, we can take the same logic and approach as we demonstrated, and apply it to a Cucumber step definition.

The Code

Let’s say that if a certain exception appears after a click we want to refresh the page and try again.  If the exception appears again we let the step fail.

The script will check to see if specified text is included after the begin. If this function fails and the text is there, it will execute the rescue, which we have specified here to display a puts string in the command line and take a screenshot at the point of failure. It will also raise an exception that includes the text variable in an output message. Lets see the step in the context of the feature file:

After running this, we will see our output as follows:

The Takeaway

The Ruby rescue 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 Cucumber step definitions and feature files.