How to wait till an element appears after an AJAX call using capybara-webkit?
Asked Answered
P

3

9

The capybara method, wait_until doesn't seems to work for capybara-webkit. Is there any alternate solution for that, or any Javascript implementations?

Intentionally need some replacement for sleep, e.g. sleep 2.

enter image description here

Pepsinogen answered 9/7, 2014 at 9:5 Comment(0)
I
10

If your AJAX call results in a change to the DOM, Capybara will wait for it if you do

page.should have_selector?("some selector")

It is an intentional Capybara feature that it waits (up to Capybara.default_wait_time) for have_selector? and related methods to be true.

If your AJAX call does not result in a change to the DOM, there's no way to wait for it on the browser side using Capybara. You might be able to detect when the AJAX call is complete in Javascript and somehow communicate that to Capybara, but that would couple your test and implementation rather tightly. A common approach in this case is to wait for the server-side effect of your AJAX call (creation or update or deletion of a model object, sending of an email, etc.) to take place. Since Capybara can't see the server side you have to wait for the server-side change yourself.

In Capybara 1 you can use Capybara's wait_until to wait for the server-side change. wait_until was removed from Capybara 2. I posted an implementation of wait_until in my answer to Why does adding "sleep 1" in an after hook cause this Rspec/Capybara test to pass?

Inquisitor answered 10/8, 2014 at 16:17 Comment(0)
M
1

I didn't really need the expectation as it wasn't what I needed to test.

This worked for me:

page.has_css?('.my-selector')
# or
page.has_content?('Some text on the page')

# continue with test
Mervin answered 19/11, 2020 at 2:55 Comment(0)
A
0

Maybe something like this:

# AJAX BEGIN
  expect(page).to have_selector('form#new_user_video .submit > .throbber')
  expect(page).to_not have_selector('form#new_user_video .submit > .throbber')
  # AJAX END

Manually in your js code set 'ajax:send' (append throbber) and 'ajax:success' (remove throbber). This way you'll be able to know when request is finished.

And you should set enough time for ajax to complete:

Capybara.default_max_wait_time = 5
Autocracy answered 5/5, 2015 at 14:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.