Search code examples
rubyconsolecapybarapoltergeist

Capybara button.click works on Console but not on a Script (Ruby; Capybara; Poltergeist)


When I do this on PRY Console:

require 'phantomjs'
require 'capybara/poltergeist'

Capybara.register_driver :poltergeist do |app|
    Capybara::Poltergeist::Driver.new(app, :phantomjs => Phantomjs.path)
end

s = Capybara::Session.new(:poltergeist)
s.visit('site')
s.fill_in('field', with: data)
s.find_button('button').trigger('click')

It works as expected.

But when I try to do the same on a ruby file, script, it fails.

Edit: Why I say it fails, I mean that the form is not submitted and therefore the page wont redirect.

Does anybody know why?

Thanks

David


Solution

  • When you call s.find_button('button').trigger('click') the mouse click occurs and it immediately returns to your code while the "browser" goes off and starts requesting the next page or whatever action the click triggers. So if you immediately call s.html it's not going to be correct since the page hasn't actually loaded at that point in time. You can either sleep for a few seconds to let the page load, or use the Capybara finders/matchers which will automatically wait (up to Capybara.default_max_wait_time seconds) until the relevant elements appear (which means they wait for the page to load). It worked in the pry console because you were waiting just by the delay in typing the next command.