Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test confirm/alert messages with capybara + headless chrome

Recently I switched my acceptance tests from capybara-webkit to headless chrome. In some cases I need to check alert messages (for example, confirm to discard changes when user leaves the page). With capybara-webkit I did it the following way

confirm_messages = page.driver.browser.confirm_messages
expect(confirm_messages.first).to include "Do you want to discard your changes?"

# or

expect(page.driver.browser.confirm_messages).to be_empty

Now when I try to get confirm messages with chrome/headless chrome I get the following error:

undefined method `confirm_messages' for #<Selenium::WebDriver::Chrome::Driver:0x007fa5478d8a08> (NoMethodError)

How can I test alerts with capybara and headless chrome?

like image 937
Hirurg103 Avatar asked Mar 05 '23 00:03

Hirurg103


1 Answers

You need to use the text parameter of Capybaras modal handling methods (accept_confirm/accept_alert/etc) -https://www.rubydoc.info/github/jnicklas/capybara/Capybara/Session#accept_confirm-instance_method - which will check the message before it accepts/dismisses the system modal

accept_confirm "Do you want to discard your changes?" do
  # whatever action triggers the modal to be shown
  click_link("Go somewhere else")
end

Technically accept_confirm also returns the text of the box so you could do something like

msg = accept_confirm do
  # action which triggers modal to be shown
end
expect(msg).to eq "Do you want to discard your changes?"

although if you know exactly the text of the message the first example reads better. Note, this would also have worked with capybara-webkit without needing to use driver specific methods.

like image 105
Thomas Walpole Avatar answered Mar 07 '23 14:03

Thomas Walpole