You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Capybara+RSpec测试中page为空触发Nokogiri语法错误求助

问题排查与解决

核心问题解析

  • 触发的Nokogiri::CSS::SyntaxError错误,本质是Poltergeist(基于PhantomJS的无头驱动)与Capybara交互时,页面DOM未正确加载或同步,导致Nokogiri解析空/异常HTML内容时出错。Nokogiri是Capybara用来解析页面HTML、处理CSS选择器的底层依赖,和jQuery无关。
  • page.html为空说明登录跳转后,Capybara未正确获取目标页面内容,大概率是页面跳转未等待完成或Poltergeist的JS渲染出现异常。

具体修复步骤

  1. 移除page.status_code.should == 200
    Capybara的page.status_code在JS驱动(如Poltergeist)下不可靠——JS渲染页面多为客户端路由跳转,不会返回HTTP状态码。且这句代码会打断Capybara的自动等待机制,导致后续断言在页面未加载完成时执行。

  2. 添加显式等待确保页面跳转完成
    替换状态码检查,改为等待登录后的标志性路径或元素,比如:

    expect(page).to have_current_path('/dashboard') # 替换为你的登录后实际跳转路径
    
  3. 调整Poltergeist配置
    检查spec_helper.rb或rails_helper.rb中的Poltergeist配置,确保启用JS渲染并设置合理超时:

    Capybara.register_driver :poltergeist do |app|
      Capybara::Poltergeist::Driver.new(app, {
        js_errors: false, # 临时关闭JS错误检查,排查是否有页面JS报错
        timeout: 30,
        phantomjs_options: ['--load-images=no', '--ignore-ssl-errors=yes']
      })
    end
    
  4. 调试时优先使用Capybara断言方法
    在pry-rescue中,优先用page.has_content?、page.has_link?这类Capybara提供的断言方法——它们会自动等待元素加载;若一定要调用page.all/page.first,先确认页面加载完成:

    page.execute_script('return document.readyState') == 'complete'
    
  5. 排查WEBrick并发问题
    WEBrick是单线程服务器,Poltergeist请求频繁时可能出现响应阻塞,可临时切换为Puma服务器测试,在spec_helper.rb中添加:

    Capybara.server = :puma, { Silent: true }
    

修正后的测试代码示例

let(:person) { create(:person) }
scenario 'works with their password', js: true do
  # Login with password
  visit '/login'
  fill I18n.t('labels.email_address'), with: person.email
  fill I18n.t('labels.password'), with: person.password
  click_button(I18n.t('actions.login'))

  # 等待页面跳转完成
  expect(page).to have_current_path('/your-dashboard-path') # 替换为实际路径

  # Verify we are logged in
  within('header') do
    expect(page).to have_link "#{person.first_name} #{person.last_name}"
  end
end

内容的提问来源于stack exchange,提问作者xeruf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 20:01:06