我已经看到了wait_for_ajax
方法的各种实现,这使得Capybara等到所有AJAX请求都完成后才能继续前进。
我刚刚切换到使用Poltergeist作为我的JavaScript驱动程序,我无法让它等待AJAX完成测试(见下文)
以下是之前使用Selenium的实现 - 我修改的唯一内容是评估脚本 -
page.evaluate_script("jQuery.active")
page.evaluate_script("$.active").to_i
如果我插入一个sleep
语句,它会通过因为它有足够的时间来完成AJAX调用,所以我肯定知道这就是问题。
这种方法有错误吗?
谢谢!
it "user can log in", js: true do
visit root_path
click_tab("log-in")
# Fill in form
fill_in "user[email]", with: "al-horford@hawks.com"
fill_in "user[password]", with: "sl4mdunkz"
# Click submit and wait for AJAX
within("#log-in") { click_button("Log In")) }
wait_for_ajax
# Expectations
expect(current_path).to eq(home_index_path)
end
def wait_for_ajax
Timeout.timeout(Capybara.default_max_wait_time) do
loop until finished_all_ajax_requests?
end
end
def finished_all_ajax_requests?
request_count = page.evaluate_script("$.active").to_i
request_count && request_count.zero?
rescue Timeout::Error
end
答案 0 :(得分:2)
根据我的经验,有些情况下wait_for_ajax不会等待。
在我们的应用程序中,我们有一个触发Ajax的'to cart'按钮。然后它在加载下一页之前等待回调事件。这不是由wait_for_ajax获取的。
修复它的原因是什么,通常比使用sleep()等待一段时间更好的方法是验证你是否使用Capybara的等待发现者进入下一页。
只需替换expect(current_path).to eq(home_index_path)
类似于expect(page).to have_content("content_home_page_should_have")
这应该有效。