如何在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
相关产品推荐
相关产品推荐

