How to wait and accept alert field with capybara / selenium

I use 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

click_buttonlaunches an unobtrusive javascript call that displays a warning popup. However, closing the notification window only succeeds in approximately 50% of test runs, I think, because the warning window is not always on the screen during the execution of the command page.driver.browser.switch_to.alert.accept. The following test script, of course, runs in "Timeout Error" if the warning window is not closed.

It always works correctly if I use sleep 1between click_buttonand ...alert.accept, but this is not a very good solution. Any idea?

+5
2

, .

wait = Selenium::WebDriver::Wait.new ignore: Selenium::WebDriver::Error::NoAlertPresentError
alert = wait.until { page.driver.browser.switch_to.alert }
alert.accept
+19
expect{
  accept_alert "Are you sure?" do
    click_link "Destroy"
  end
  sleep 1.second # !important
}.to change(Post, :count).by(-1)
+1

Source: https://habr.com/ru/post/1527482/


All Articles