The Issue

When  conducting browser testing, you will eventually encounter a browser Javascript alert. These can appear to be initially tricky, as attempting to treat them as a regular element won’t work; inspect element does not show an identifier for any of the options on the browser alert. In order to interact with them, we will need to utilize a specific Ruby & Watir Webdriver command in our automated test.

The Answer

We will use the following to interact with browser alerts:

The browser.alert command will allow us to interact with the alert in a variety of ways listed above. For our purposes, we will be looking at the browser.alert.ok and browser.alert.close commands

The Code

Lets use a simple alert for our example. On the page we can click a button to cause an alert to appear. We will use the browser.alert.ok Watir Webdriver command to close the alert.

Alternatively, we can use the browser.alert.close command to close the alert.

Our browser alert which we can close with our Watir-Webdriver command.

Our browser alert which we can close with our Watir-Webdriver command.

The Result

We can save both of the above ruby automated tests and run them from our command line. Here are the resulting steps:

  • Browser opens
  • Browser navigates to the page containing our alert button
  • Browser clicks the alert button, causing alert to appear
  • Browser closes alert (through either browser.alert.close or browser.alert.ok

The Takeaway

When encountering a browser alert for the first time, figuring out how to deal with it can be frustrating. They won’t appear when attempting to inspect element, and they will prevent you from moving forward without knowing how to deal with them. You’re now equipped with a Ruby & Watir Webdriver command to handle browser alerts while building your test automation.