Skip to main content
 首页 » 编程设计

jquery之在 Rails 中的 Cucumber + Capybara + PhantomJS 中调试 jQuery Ajax

2026年10月07日5exmyth

我很难解决这个问题,因此我们将不胜感激任何帮助。

我想做的就是在我的项目上测试一个简单的基于 Ajax 的注册表单。如果表单提交成功,您将被重定向到欢迎页面。如果不是,您会收到与每个违规字段相关的相应验证错误。

出于某种奇怪的原因,Capybara 没有遵循重定向。正在进行 Ajax 调用,我看到数据库中注册了一个新帐户,但 onSuccess 回调根本没有被调用,或者重定向被忽略。

这是我正在尝试使用的内容(为了简洁起见,我压缩了代码):

功能:

  Feature: Registration 
    In order to obtain a new account 
    As a prospective customer 
    I must submit a valid registration form. 
 
    @javascript 
    Scenario: A valid registration attempt 
      Given an account registration form 
      When I complete the form with valid values 
      Then I should be redirected to the welcome screen  

测试:

Given(/^an account registration form$/) do 
  visit("/signup") 
  assert current_path == "/signup" 
end 
 
When(/^I complete the form with valid values$/) do 
  within("#signupForm") do 
    fill_in("email",    :with => Faker::Internet.email) 
    fill_in("name",     :with => Faker::Name.name) 
    fill_in("password", :with => "11111111") 
 
    click_link("signupFormSubmit") 
  end 
end 
 
Then(/^I should be redirected to the welcome screen$/) do 
  assert current_path == "/welcome" 
end 

JavaScript:

console.log('I am not yet inside you.') 
 
$.post(url, form.serialize(), function(response) { 
  // everything went well 
  // let's redirect them to the given page 
  window.location.replace(response.redirectUrl) 
  console.log('I am inside you and it is good.') 
}, function(response) { 
  // collect error responses from API 
  // apply error hints to associated fields 
  console.log('I am inside you and something went wrong.') 
}) 

好吧,所以这个特定的测试运行得很好,直到我们到达我们应该将用户重定向到欢迎屏幕的位置。我已尽一切努力查看 onSuccess、onFailure 回调中发生的情况,但无济于事。就像代码根本没有被执行一样。

我刚刚从测试运行中得到以下输出:

Then I should be redirected to the welcome screen # features/step_definitions/registration.rb:51 
  Failed assertion, no message given. (MiniTest::Assertion) 
  ./features/step_definitions/registration.rb:52:in `/^I should be redirected to the welcome screen$/' 
  features/registration.feature:15:in `Then I should be redirected to the welcome screen' 

即使我提出异常也没关系,它不会被接受。回调中对 console.log() 的调用也不会。

有人看过这个吗?如果是这样,有解决方法吗?如果您需要更多信息,请直接询问,我非常乐意提供。

请您参考如下方法:

根据robots at Thoughtbot Coderwall 的人员,您可以使用辅助方法来完成此操作,并将其放入 spec/support 中。 他们将模块命名为 WaitForAjax:

# spec/support/wait_for_ajax.rb 
module WaitForAjax 
  def wait_for_ajax 
    Timeout.timeout(Capybara.default_wait_time) do 
      loop until finished_all_ajax_requests? 
    end 
  end 
 
  def finished_all_ajax_requests? 
    page.evaluate_script('jQuery.active').zero? 
  end 
end 

从那里,您只需将其加载到您的测试框架中即可;对于 Rspec,这可以在规范/配置文件中完成,也可以通过简单地将一些代码添加到模块文件的末尾来完成:

RSpec.configure do |config| 
  config.include WaitForAjax, type: :feature 
end 

确保在您的配置文件中要求 spec/support/**/*.rb,但您可能无论如何都应该这样做。

http://www.elabs.se/blog/53-why-wait_until-was-removed-from-capybara

当然,根据上面的博客文章,如果您只是寻找欢迎页面独有的选择器,则可能根本不需要,也可能根本不需要,具体取决于您构建页面的方式。