Capybara每次重定向结束会话,点击链接跳转登录页问题求助
问题根本原因
- 你在测试
before钩子中先使用rack_test驱动完成登录,再切换到selenium_firefox驱动:Devise/Warden提供的login_as测试助手生成的登录态仅作用于当前驱动的会话,两个驱动的上下文完全隔离,Selenium驱动启动的真实浏览器没有继承到登录状态,跳转登录是未登录的正常表现。 - 你手动固定了Capybara的服务端口为3002,若此时本地同时运行了监听3002端口的Rails开发服务,Selenium访问的会是开发环境服务,测试库中FactoryBot创建的用户不存在于开发库中,也会导致未登录跳转。
修复方案
方案一:走真实前端登录流程(兼容性最高,无驱动适配问题)
移除before块中切换驱动的冗余逻辑,直接在Selenium驱动下走标准登录流程,修正后的测试代码如下:
require 'rails_helper' require 'webdrivers' RSpec.describe "Searches", driver: :selenium_firefox, js: true, type: :system do before do user = FactoryBot.create(:user) # 直接走真实页面登录流程 visit new_user_session_path fill_in '邮箱', with: user.email # 注意FactoryBot创建用户时需要设置统一默认密码,例如"123456" fill_in '密码', with: '123456' click_button '登录' end it "populate movie form" do visit search_path find('#home_path').click sleep(3) end end
方案二:配置Warden测试模式保留login_as用法
如果需要保留login_as的简化写法,需要先在rails_helper.rb中开启Warden测试模式:
# 新增Warden测试配置 Warden.test_mode! RSpec.configure do |config| config.after(:each) do Warden.test_reset! end end
测试代码修改为:
require 'rails_helper' require 'webdrivers' RSpec.describe "Searches", driver: :selenium_firefox, js: true, type: :system do before do user = FactoryBot.create(:user) login_as(user, scope: :user, run_callbacks: false) end it "populate movie form" do visit search_path find('#home_path').click sleep(3) end end
额外配置调整
删除spec_helper.rb中手动设置的固定端口配置:
# 移除以下三行配置,Capybara默认会自动分配端口、匹配服务地址,无需手动指定 Capybara.app_host = "http://localhost:3002" Capybara.server_host = "localhost" Capybara.server_port = "3002"
如果确实需要固定端口,测试运行前必须确认3002端口未被开发环境等其他服务占用。
内容的提问来源于stack exchange,提问作者Saoma
相关产品推荐
相关产品推荐

