How to map browser dialog using capybara/selenium

246 Views Asked by At

What is the best way to handle browser dialogs (with ok/cancel buttons) using capybara/selenium?

The way I found easiest is by running the following:

dialog = page.driver.browser.switch_to.alert
dialog.accept

Any thoughts for a better approach?

Whoever downed this post please give a valid reason... it's not helpful to down vote with no reason why

1

There are 1 best solutions below

1
On BEST ANSWER

Where possible, you should try to avoid using the underlying driver directly. By using Capybara's API, you would be (in theory) in a better position if you want to change driver's and there are driver API differences.

From Capyabara's project page, the way to handle modal dialogs is:

In drivers which support it, you can accept, dismiss and respond to alerts, confirms and prompts.

You can accept or dismiss alert messages by wrapping the code that produces an alert in a block:

accept_alert do
  click_link('Show Alert')
end

You can accept or dismiss a confirmation by wrapping it in a block, as well:

dismiss_confirm do
  click_link('Show Confirm')
end

You can accept or dismiss prompts as well, and also provide text to fill in for the response:

accept_prompt(with: 'Linus Torvalds') do
  click_link('Show Prompt About Linux')
end

All modal methods return the message that was presented. So, you can access the prompt message by assigning the return to a variable:

message = accept_prompt(with: 'Linus Torvalds') do
  click_link('Show Prompt About Linux')
end
expect(message).to eq('Who is the chief architect of Linux?')