Ryan Drake
Ryan Drake

Reputation: 643

Rails + Capybara: 'Unexpected Alert Open' for Selenium Driver

I am using Capybara and Chrome as my default selenium browser.

Test:

it "is successful with deleting a user", js: true do
  visit '/users'
  expect(User.count).to eq(1)
  expect(user.email).to eq("[email protected]")
  expect(page).to have_content("Manage Users")
  click_link 'Delete User'
  page.driver.browser.confirm.accept
  user.reload
  visit '/users'
  expect(User.count).to eq(0)
end

I'm getting this error for my test:

Failure/Error: visit '/users'
 Selenium::WebDriver::Error::UnhandledAlertError:
   unexpected alert open

I have tried the following in my test:

page.driver.browser.switch_to.confirm
page.driver.browser.switch_to.accept
page.driver.browser.confirm.accept

Any other variations I should try with my test?

Upvotes: 25

Views: 10994

Answers (2)

OfficeYA
OfficeYA

Reputation: 735

I just got the same error.

Checking the capybara documentation at rubydoc.info, I found that the following methods solve the issue:

accept_confirm: "Execute the block, accepting a confirm."

dismiss_confirm: "Execute the block, dismissing a confirm."

Upvotes: 2

Rob Wise
Rob Wise

Reputation: 5120

Try wrapping the code that will initiate the alert prompt inside of an accept_alert block, like this:

it "is successful with deleting a user", js: true do
  visit '/users'
  expect(User.count).to eq(1)
  expect(user.email).to eq("[email protected]")
  expect(page).to have_content("Manage Users")

  # Change is here:
  accept_alert do
    click_link 'Delete User'
  end

  user.reload
  visit '/users'
  expect(User.count).to eq(0)
end

I'm a little concerned that you would want to use an alert rather than a confirmation when deleting a resource, but that's up to you. An alert is just going to tell you that something is going to happen, meanwhile a confirmation allows the user to change their mind by hitting cancel instead of OK. If you use a confirmation modal instead of an alert modal then the accept_alertpart would need to be changed to accept_confirm.

Check out the modal documentation rubydoc for more info.

Upvotes: 49

Related Questions