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

如何在Rspec Capybara中模拟按下Tab键?

RSpec Capybara 模拟按下Tab键的方案

基础实现

Capybara 提供了原生的send_keys方法可以直接模拟键盘按键,针对Tab键的场景有两种常用写法:

  • 给当前页面聚焦的元素发送Tab键:
# 单次按Tab键
page.active_element.send_keys :tab

# 按Shift+Tab实现反向焦点跳转
page.active_element.send_keys [:shift, :tab]
  • 给指定元素发送Tab键(一般用于先聚焦某个元素后触发跳转):
# 先定位目标元素,再触发按键
find("#dialog-confirm-btn").send_keys :tab

注意事项

以上写法仅支持支持JS交互的驱动(比如Selenium、Playwright驱动),默认的RackTest驱动不支持键盘事件模拟,你需要给测试用例加上js: true标记启用支持JS的驱动,示例如下:

RSpec.describe "对话框焦点逻辑", type: :feature, js: true do
  it "Tab键在弹窗内正常循环跳转" do
    click_button "打开弹窗"
    within ".modal-container" do
      # 校验初始聚焦在关闭按钮
      expect(find(".modal-close-btn")).to have_focus
      # 按Tab跳转焦点
      page.active_element.send_keys :tab
      # 校验焦点跳转到输入框
      expect(find("#modal-email-input")).to have_focus
    end
  end
end

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 02:24:02