黄瓜:等待ajax:成功

我在Rails 3.1项目中有以下典型的黄瓜步骤:

... When I follow "Remove from cart" Then I should see "Test Product removed from cart" 

困难在于“从购物车中删除”按钮是一个ajax:远程调用,它通过以下方式将“从购物车中删除测试产品”返回到#cart_notice元素:

 $('#cart_notice').append(" removed from cart"); 

该function在浏览器中工作正常,但没有在黄瓜中找到“从购物车中删除测试产品”文本。 我猜这是因为Cucumber在AJAX返回之前正在搜索文本?

所以,简而言之…如何确保黄瓜在搜索所需内容之前等待ajax返回结果?

要添加到dexter所说的内容,您可能需要编写一个在浏览器中执行JS的步骤,该步骤等待ajax请求完成。 使用jQuery,我使用这一步:

 When /^I wait for the ajax request to finish$/ do start_time = Time.now page.evaluate_script('jQuery.isReady&&jQuery.active==0').class.should_not eql(String) until page.evaluate_script('jQuery.isReady&&jQuery.active==0') or (start_time + 5.seconds) < Time.now do sleep 1 end end 

然后,您可以根据需要或在每个javascript步骤之后包含该步骤:

 AfterStep('@javascript') do begin When 'I wait for the ajax request to finish' rescue end end 

我遇到了自动同步的问题,这清除了它。

我猜你正在用黄瓜和水豚。 在这种情况下,capybara带有resynchronizefunction。 "Capybara can block and wait for Ajax requests to finish after you've interacted with the page." - from capybara documentation

您可以在features/support/env.rb启用它

 Capybara.register_driver :selenium do |app| Capybara::Driver::Selenium.new(app, :browser => browser.to_sym, :resynchronize => true) end 

但是,我已经看到这导致超时问题。 因此,如果这对您不起作用,我建议在断言ajax请求的结果之前引入手动等待步骤。

 ... When I follow "Remove from cart" And I wait for 5 seconds Then I should see "Test Product removed from cart" 

您可以在step_definitions/web_steps.rb中将等待步骤定义为

 When /^I wait for (\d+) seconds?$/ do |secs| sleep secs.to_i end 

我想wait_until应该做的。 它将命令capybara检查一些东西,直到它真实一段时间。

老问题,但Spreewald gem应该有帮助https://github.com/makandra/spreewald

您可以使用Spreewald gem中的耐心方法,如下所示:

 Then /^I should see "([^\"]*)" in the HTML$/ do |text| patiently do page.body.should include(text) end end 

该步骤将保持循环一段时间,直到所需文本出现在测试dom中,否则该步骤将失败。

(摘自https://makandracards.com/makandra/12139-waiting-for-page-loads-and-ajax-requests-to-finish-with-capybara )