I'm using the following code in my rspec test:
describe "Save should create a BasketItem and a Basket" do
subject {
lambda {
click_button I18n.t(:create_basket_and_add_items)
page.driver.browser.switch_to.alert.accept # close the alert box
}
}
it { should change(BasketItem, :count).by(1) }
it { should change(Basket, :count).by(1) }
end
The click_button
fires an unobtrusive javascript call, which displays an alert popup window. However closing the alert box is successfully only in about 50% of the test runs, I guess because the alert box is not always on the screen already at the time of the command page.driver.browser.switch_to.alert.accept
is running. The next test case runs into "Timeout Error" of course, if the alert box is not closed.
It works always correctly if I'm using sleep 1
between click_button
and ...alert.accept
, but it is not a very nice solution. Any idea?
Here is some code that I've used for this.
wait = Selenium::WebDriver::Wait.new ignore: Selenium::WebDriver::Error::NoAlertPresentError
alert = wait.until { page.driver.browser.switch_to.alert }
alert.accept