How do I confirm a javascript popup with Capybara?

2019-01-21 16:00发布

I've tried several examples found online, but with no luck. I am looking to confirm the confirm message of a delete link. The last attempt was the code below, but that resulted in an Capybara::NotSupportedByDriverError error.

def confirm_dialog
  page.evaluate_script('window.confirm = function() { return true; }')
end

8条回答
Ridiculous、
2楼-- · 2019-01-21 16:30

First of all switch to using Selenium as the driver by putting an @javascript tag in front of your scenario.

The following code in your cucumber step will then confirm the dialogue:

page.driver.browser.switch_to.alert.accept
# or
page.driver.browser.switch_to.alert.dismiss
# or
page.driver.browser.switch_to.alert.text

As @NobbZ said, this question has been asked and answered before here: How to test a confirm dialog with Cucumber?.

More selenium documentation available here too: http://code.google.com/p/selenium/wiki/RubyBindings#JavaScript_dialogs

查看更多
Rolldiameter
3楼-- · 2019-01-21 16:30

I've had timing issues with browser dialogs in a CI environment so I'm polling for a dialog before accepting it:

def accept_browser_dialog
  wait = Selenium::WebDriver::Wait.new(:timeout => 30)
  wait.until {
    begin
      page.driver.browser.switch_to.alert
      true
    rescue Selenium::WebDriver::Error::NoAlertPresentError
      false
    end
  }
  page.driver.browser.switch_to.alert.accept
end
查看更多
登录 后发表回答