Hi Navi,
At this point, I would say there is a design flaw in Page-Object's #alert method, which does:
if @browser.alert.exists?
value = @browser.alert.text
@browser.alert.ok
end
The
conditional check is likely the cause of your problem. I don't know the
history of how we got here, but my guess is that we wanted to handle
controls that randomly created alerts.
Unfortunately, this can be
easily thrown off. I assume your div does not immediately trigger the
alert. There is probably some sort of processing and/or asynchronous
call that happens before deciding to show the alert. This can be enough
to cause problems - ie:
# Div is clicked
# Some JavaScript starts to determine if the alert should appear
# #alert checks if an alert exists or not, finds nothing so just moves on (ie no alert to dismiss)
# The JavaScript finishes processing, displaying the alert
# The next Watir command fails since the alert is still there
You
can see how little is required to create the timing issue. The
following page has a div, that when clicked waits 10ms before displaying
the alert.
<!doctype html>
<html>
<head>
<script>
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function run() {
await sleep(10); // (in milliseconds) slight delay before alert is triggered
alert("test");
}
</script>
</head>
<body>
<div class="select-checkbox" onclick="run();">asdf</div>
</body>
</html>
The following page-object clicks this div but does not dismiss the alert. The exception then occurs on the next command:
class MyPage
include PageObject
def do_stuff
alert do
div.click
end
sleep(1) # ensure alert has appeared
p div.text
#=> Selenium::WebDriver::Error::UnhandledAlertError
end
end
page = MyPage.new(browser)
page.do_stuff
I would be curious if you added a #sleep to your code if that would address the problem:
click
sleep(10) # add this sleep to ensure that the alert appears before proceeding
end
sleep(10)
puts alert_text
Though
if that solves your problem, I do not think the #alert method is adding
any value. You know the alert is going to appear, so you may as well
call Watir's alert code (ie Titus' example), which would include
automatic waiting.
Justin