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.
A popular use case for alerts is in the case of error prevention for password restrictions.
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.
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
@driver = Selenium::WebDriver.for :firefox
Now let's write our test.
popup = @driver.switch_to.alert
result = @driver.find_element(id: 'result').text
expect(result).to eql('You clicked: Ok')
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
switchTo().alert(). After accepting/dismissing the alert, our main browser window will automatically regain focus and the page will display the result.
About The Author
Dave Haeffner is the original writer of Elemental Selenium -- a free, once weekly Selenium tip newsletter that's read by thousands of testing professionals. He also created and maintains the-internet (an open-source web app that's perfect for writing automated tests against).
Dave has helped numerous companies successfully implement automated acceptance testing; including The Motley Fool, ManTech International, Sittercity, and Animoto. He is also an active member of the Selenium project and has spoken at numerous conferences and meetups around the world about automated acceptance testing.