Emil Ahlbäck
Emil Ahlbäck

Reputation: 6206

How to tell capybara-webkit to not ignore confirm boxes (or simply test their content)

So I have a scenario:

Given I signed in to my business account
And there is one customer named "Samantha Seeley"
When I go to the customers management page
Then "Delete" should show a confirmation dialog saying "Are you sure?"

The link is simply:

<%= link_to 'Delete' customer_path(customer), method: :delete, confirm: 'Are you sure?' do %>

So this code does make a confirmation dialog appear when I click on the link in Chrome, but using page render like this:

Then /^"(.*?)" should show a confirmation dialog saying "(.*?)"$/ do |arg1, arg2|
  click_on arg1
  page.driver.render "tmp/screenshot.jpg"
end

I believe I can confim that the javascript does not seem to be evaluated (no confirmation dialog is shown) from the screenshot. This assumption might be wrong though, I'm not sure.

Thanks for your help.

Upvotes: 3

Views: 1603

Answers (1)

georgebrock
georgebrock

Reputation: 30043

There was a similar issue raised on GitHub: https://github.com/thoughtbot/capybara-webkit/issues/84

The conclusion was to use something like this, which was suggested by Jesse Cooke and Ken Collins:

def handle_js_confirm(accept=true)
  page.evaluate_script "window.original_confirm_function = window.confirm"
  page.evaluate_script "window.confirm = function(msg) { return #{!!accept}; }"
  yield
ensure
  page.evaluate_script "window.confirm = window.original_confirm_function"
end

This won't help you test the contents of the confirm dialog (although it could easily be extended to do so), but it will allow you to test what happens when the user clicks either OK or Cancel.

In this specific case, you're expecting a confirmation dialog because you're using a Rails helper that generates one. It's worth thinking about whether or not this needs test coverage in your own app; there are already tests in Rails to cover it.

Upvotes: 5

Related Questions