Question

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?

Was it helpful?

Solution

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

OTHER TIPS

expect{
  accept_alert "Are you sure?" do
    click_link "Destroy"
  end
  sleep 1.second # !important
}.to change(Post, :count).by(-1)

This is my solution, nothing else worked:

  scenario 'admin deletes user', js: true do
    within(confirmed_user_row) do
      expect {
        accept_confirm do
          click_link_or_button('Delete')
        end
        sleep(0.5) # or it checks too quick as entry in db not updated yet
      }.to change(User, :count).by(-1)
    end

    expect(page).to have_content("User was deleted from system.")
  end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top