Search code examples
ruby-on-railsruby-on-rails-4seleniumcapybara

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("ryan@drake.com")
  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?


Solution

  • 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("ryan@drake.com")
      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.