Search code examples
rspeccapybarapoltergeist

Unable to force a click of a hidden element with Capybara


I have an intermittent failure in my capybara tests caused by a modal not closing quickly enough and so covering the button that is to be clicked. The error message from Capybara tells me to try node.triger('click'). When I try this with the following code

find_button('Update').trigger('click')

I get this error:

 Failure/Error: find_button('Update').trigger('click')

 Capybara::NotSupportedByDriverError:
   Capybara::Driver::Node#trigger    

I am using the poltergeist driver e.g. in my rails_helper I have

Capybara.javascript_driver = :poltergeist

What is happening?


Solution

  • When you need a request or animation to finish in order for the next test to work, a solid strategy is to write a test that causes Capybara to wait until it passes. For example, if your modal with selector .modal disappears after clicking an OK button, you could write a test like:

    click_button 'OK'
    expect(page).not_to have_css '.modal'
    click_button 'Update'
    

    By default, Capybara waits for two seconds for animations and async requests to finish before failing a test. That can be configured with Capybara.default_max_wait_time = 5 to change it to 5 for example.