Built into Selenium is the ability to switch to an alert window and either accept or dismiss it. This way your tests can continue unencumbered by dialog boxes that may feel just out of reach.
Let's dig in with an example.
First, we'll include our requisite libraries (e.g.,
selenium-webdriver to control the browser and
RSpec::Matchers for our assertion) and wire up some simple
Now let's write our test.
find_elements and click on the second one. Since
find_elements returns an Array of all found elements, we can assume that the first item can be selected using
 (since Arrays in Ruby start counting at
0). So the second item would be
.accept to click
Ok. If we wanted to click
Cancel we would have used
After accepting the alert, our main browser window will automatically regain focus and the page will display the result that we chose. This text is what we use for our assertion, making sure that the words
You clicked: Ok are displayed on the page.
If you save this file and run it (e.g.,
- Open the browser
- Load the page
- Click the second button on the page
- Assert that the result on the page is what we expect
- Close the browser