The Issue

Using a local variable with Ruby will allow you to define a value and reuse it with ease within your scripts or step definitions. Local variables are local to the script/code that they are defined within. If we define a local variable within a method or loop, you will not be able to access it outside of that method/loop. These variables are fundamental to constructing automation scripts and will optimize your Watir Webdriver/Selenium script runs/maintenance.

The Code

Here are two examples of the same script; the first is not utilizing local variables:

The second script, seen below, defines the local variable before the steps that utilize the variable.

Since we have defined the local variable as the target in the above example, we can reuse it across the rest of the script. As we continue, the variable is utilized across our Watir Webdriver actions, validating if the text is included, and putting a message containing the target, depending on the result.

The Takeaway

Ruby local variables are essential to condensing your Watir Webdriver/Selenium scripts and can stop you from unnecessarily repeating lines of code as your scripts scale up. This is especially the case with building out Cucumber step definitions; rolling up steps into variables and reusing them is an important aspect of optimizing your code.