Rails 7 API下RSpec测试Devise注册时Session设置异常问题
问题:Rails 7 API + Devise 注册场景下的RSpec Session设置问题
基于Rails 7 API + Ruby 3.1.2实现群组邀请注册逻辑:用户通过邀请链接注册时,群组ID存入Session,注册完成后自动成为群组成员。使用Devise做身份验证,自定义了RegistrationsController:
class Users::RegistrationsController < Devise::RegistrationsController def create super if @user # 若Session中有群组ID(说明是受邀注册),则创建成员关系 Membership.create(user: @user, group: session[:group]) if session[:group] # 清除现有Session reset_session end end end
手动测试功能正常,但在RSpec测试携带Session注册的场景时遇到问题。测试代码尝试多种写法均报错:
- 直接在
post请求中传:session参数,抛出ArgumentError: unknown keyword: :session - 将Session放入params,抛出
NoMethodError: undefined method 'enabled?' for {}:Hash - 先发送请求再设置
request.session[:group],断言通过但控制器无法获取Session - 直接设置
session[:group],抛出NoMethodError: undefined method 'session' for nil:NilClass
解决方案
在Rails API模式的RSpec请求测试中,正确设置Session的方式是在发送请求前,通过request.session设置会话值,调整后的测试代码如下:
context "when user signs up via invitation" do let(:group) { create(:group) } before do # 先创建依赖的图标 create(:icon) # 发送请求前设置Session request.session[:group] = group.id # 发送注册请求 post user_registration_path, params: { user: { username: "test", email: "myemail@email.com", password: "mypassword" } } end it "automatically adds the user to the invited group" do # 验证成员关系是否创建(原断言Session会失败,因为控制器调用了reset_session清空会话) expect(Membership.exists?(user: User.last, group: group)).to be true end end
关键说明
- Rails API模式下,RSpec请求测试中必须通过
request.session来设置会话,不能将Session作为请求参数传递 - 原测试中断言
session[:group]会失败,因为控制器中调用了reset_session,注册完成后Session已被清空,应改为验证成员关系是否正确创建 - 确保
application.rb中已正确配置Session存储(你已完成此配置):# Configure session storage config.session_store :cookie_store, key: '_interslice_session' config.middleware.use ActionDispatch::Cookies config.middleware.use config.session_store, config.session_options
内容的提问来源于stack exchange,提问作者josegp
相关产品推荐
相关产品推荐

