使用 Rails 7 API 在 RSpec 中设置会话

问题描述 投票:0回答:0

我正在尝试创建一个逻辑,用户可以在其中获得来自群组的邀请。如果他们通过该邀请注册,组 ID 将存储在会话中,当他们注册时,他们将作为成员自动添加到组中。

我正在使用

Devise
进行身份验证。所以我定制成这样:

class Users::RegistrationsController < Devise::RegistrationsController
  def create
    super
    if @user
      # We create a membership to the group if the user had it in the session (it means that it was invited)
      Membership.create(user: @user, group: session[:group]) if session[:group]
      # We remove the existing session
      reset_session
    end
  end
end

现在,我想测试这个行为。 我想测试 2 个场景:

  1. 用户没有会话并像那样注册
  2. 用户进行会话并注册 -> 生成组成员资格

第一个很好,但第二个是我正在努力的那个:

context "when user signs up via invitation" do
 let(:group) {create :group}

 before do
  # We need to create an icon so that we can attach it to the use when created
  create :icon
  
  post user_registration_path,
  params: { "user": { "username": "test", "email": "[email protected]", "password": "mypassword" }},
  session: { "group": group.id }
 end

 it "has a session saved with group id" do
  expect(session[:group]).to eq group.id
 end
end

我在这里找到了这种方式,但是它抛出了以下错误:

ArgumentError:
       unknown keyword: :session

我也试过这样设置:

request.session[:group] = group.id

在我拨打

post
电话之后(只有参数)。它确实超出了预期,但我无法从控制器中获取它。

还有,就是这样设置:

session[:group] = group.id

抛出以下错误:

NoMethodError:
       undefined method `session' for nil:NilClass
     
             @request.session

最后,如果我尝试在

before {}
块中模拟它:

allow_any_instance_of(ActionDispatch::Request).to receive(:session).and_return( group: group.id )

它给了我以下错误:

NoMethodError:
       undefined method `enabled?' for {:group=>1}:Hash
     
               return unless session.enabled?

关于如何解决这个问题的任何想法?

PD。使用 Rails 7 API 和 ruby 3.1.2

谢谢!

ruby-on-rails session rspec rspec-rails
© www.soinside.com 2019 - 2024. All rights reserved.