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

Capybara::ElementNotFound:折叠导航栏元素无法识别的问题求助

解决Capybara测试中导航栏折叠导致的ElementNotFound错误

问题背景

测试导航栏元素时触发Capybara::ElementNotFound错误,save_and_open_page显示页面HTML正常,但save_and_open_screenshot发现导航栏处于折叠状态(仅显示汉堡菜单),导致目标链接无法被点击。此前测试正常,怀疑与无头浏览器运行环境有关,但找不到触发失败的变更。

测试代码:

# frozen_string_literal: true

feature "Users can view their data", js: true do
  let!(:user) { create(:user) }

  before do
    login_as(user)
    visit root_path
  end

  scenario "with valid credentials" do
    click_link t(:user_profile)

    fill_in t("activerecord.attributes.user.email"), with: user.email
    fill_in t("activerecord.attributes.user.password"), with: "password"
    click_button t(:update)

    expect(page).to have_content(t("activerecord.attributes.user.username"))
    expect(page).to have_content(t("activerecord.attributes.user.email"))
    expect(page).to have_content(t("activerecord.attributes.user.password"))
  end
end

渲染的导航栏HTML:

<div class='collapse navbar-collapse' id='navbarSupportedContent'>
  <ul class='navbar-nav mr-auto'>
    <li class='nav-item active'>
      <a class='nav-link' href='#'>
        Home
        <span class='sr-only'>(current)</span>
      </a>
    </li>
    <li class='nav-item'>
      <a class='nav-link' href='/pages/about'>About</a>
    </li>
    <li class='nav-item'>
      <a class='nav-link' href='/users/edit'>Mijn profiel</a>
    </li>
    <li class='nav-item'>
      <a class="nav-link" rel="nofollow" data-method="delete" href="/users/sign_out">Log uit</a>
    </li>
  </ul>
</div>

核心原因

无头浏览器默认使用较小的窗口尺寸,触发了响应式导航栏的折叠断点(比如Bootstrap默认在窗口宽度<992px时折叠导航栏),导致目标链接被隐藏在collapse容器中,Capybara无法定位到可见的链接元素。而save_and_open_page仅保存HTML源码,不反映实际渲染的可见状态,所以看起来正常。

解决方案

1. 调整无头浏览器的窗口尺寸

在Capybara配置中设置足够大的窗口尺寸,避免触发响应式折叠:

# 示例:配置Chrome无头浏览器窗口大小
Capybara.register_driver :selenium_chrome_headless do |app|
  options = Selenium::WebDriver::Chrome::Options.new
  options.add_argument('--window-size=1920,1080') # 设置为桌面级分辨率
  Capybara::Selenium::Driver.new(app, browser: :chrome, options: options)
end

# 或者在测试用例中临时设置
before do
  login_as(user)
  visit root_path
  page.driver.browser.manage.window.resize_to(1920, 1080)
end

2. 测试时先展开折叠的导航栏

如果不想修改全局窗口配置,可以在测试中先检查并点击汉堡菜单,再操作目标链接:

scenario "with valid credentials" do
  # 检查是否有可见的汉堡按钮,有的话点击展开导航栏
  if page.has_css?('.navbar-toggler', visible: true)
    click_button(class: 'navbar-toggler')
    # 等待导航栏展开(可选,确保元素可见)
    find('#navbarSupportedContent', visible: true)
  end
  
  click_link t(:user_profile)

  # 后续测试步骤不变...
end

3. 确认响应式断点配置

检查项目中导航栏的折叠断点设置(比如自定义的CSS或框架配置),确保测试窗口尺寸超过该断点值,即可避免导航栏折叠。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 02:10:40