The Issue

Testing browser pages that load their elements slowly or dynamically (not all at once) can cause problems when constructing automation scripts against them. If a Selenium or Watir Webdriver command attempts to interact with an element that has not yet loaded, it will throw an error or give an undesired result. Implementing a hard-coded sleep may be a workaround, but including this for every step, and leaving extra room for loading time, will start to slow down your automation scripts unnecessarily. This is where Explicit Waits come in.

The Answer

With an Explicit Wait in your automated test, you are free to set your action and timeout, meaning Watir Webdriver will try to execute this action (within a certain timeframe) before throwing you an error. To utilize an Explicit Wait, we’ll be looking at the when_present command:

This command will wait until your specified element is loaded, and the action will be executed against the element. If you do not set your timeout, the default with Watir Webdriver is 30 seconds. If you wish to set a timeout (per the second line of code), you can specify the seconds within parentheses after the command.

The Code

Lets use when_present in our test automation script to click through SAP Fiori’s trial page, and validate the text of a page header. The when_present command is necessary for this web page, as there is a few seconds of loading time between the pages where not every element will be available.

The when_present will be attached to each click command we have in the code. Here is the script we use:

The Result

We can save the automated test script (ExplicitWait.rb) and run it from the command line. Here is a breakdown of the result:

  • Browser opens
  • Browser navigates to SAP Fiori’s homepage
  • Clicks on I Agree to enter the homepage
  • Clicks on the My Time Events tile
  • Validates that the header My Time Events exists

We will see the result in the command line, displaying a message confirming our header is validated:

Our validation was successful.

Our validation was successful.




For context, if we had NOT included the when_present in our click commands, we would have been thrown an error on the first click command. Here is a screenshot of the command line after encountering this error:

An error displays, telling us the element cannot be located.

An error displays, telling us the element cannot be located.

Again, this error would display because the browser is trying to click the element before it is present. Because the element cannot be found immediately, the error displays.

The Takeaway

Explicit Waits are vital when constructing your automated browser scripts. They allow your Selenium & Watir Webdriver commands to react to most common element loading issues that may be encountered in your automated browser testing. Simple to implement, they can act as a quick fix or be an integral part of your test scripts.