Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait for and accept an alert box with capybara/selenium

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?

like image 649
Tibor Nagy Avatar asked Feb 18 '14 10:02

Tibor Nagy


2 Answers

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
like image 124
Tim Moore Avatar answered Nov 16 '22 04:11

Tim Moore


expect{
  accept_alert "Are you sure?" do
    click_link "Destroy"
  end
  sleep 1.second # !important
}.to change(Post, :count).by(-1)
like image 3
Alexei.B Avatar answered Nov 16 '22 05:11

Alexei.B