Written by Aidy.

When you first start trying to automate web testing there's one issue that you'll probably run into fairly quickly. Webpages don't always load that quickly and there's also the added problem of the buttons, iFrames, links and other elements loading slowly too. This can result in an automated test failing due to something like trying to click a button that hasn't loaded yet. So let's look at waiting!

Sleep is used to specify an exact wait in seconds, the seconds are specified in brackets after the command. In this example we'll end up waiting for 5 seconds. It's considered bad practice to use sleep in web automation due the potential inaccuracy of either waiting too long or not long enough for something to happen. However that doesn't mean you should dismiss them entirely. They can have their uses. E.g. testing a specific time-out on a webpage.


This is a much safer way to wait and whatever we put in the curly brackets, shown in the example below is what we'll end up waiting for. So we could wait for a specific element to exist or for any other statement to become true. In the following example we're waiting for a button to exist using the exists? command. We could also wait for something like a variable to become equal to a certain value.

Watir::Wait.until{b.button(:id, 'button01').exists?}

Just to clarify, the exists? command that's used in the previous example is generally used to check if a specific element exists on a webpage, such as a button or a div.

This works in the same way as exists? but obviously it waits until an element is visible. There can be situations where an element exists but is not visible. For example a page may load with a lightbox that displays for a few seconds in front of a button we want to click. So if we used exists? then we'd still be attempting to click something that wasn't clickable yet, so visible? would be a better option in this case.

Watir::Wait.until{b.button(:id, 'button01').visible?}

The includes? command can be used to wait for some text to exist on a webpage before continuing. The example below will wait until the webpage being tested includes the text 'Hello World'.

Watir::Wait.until{b.text.include? 'Hello World'}