ruby 使用RSpec作为特定用户登录

busg9geu  于 2023-04-20  发布在  Ruby
关注(0)|答案(2)|浏览(125)

我正在尝试规范以下内容。
我需要返回链接到登录用户的所有实体。随后,我需要在事实发生之前创建用户,然后确保特定用户登录。我正在努力通过控制器宏实现这一点。我的规格失败如下
1)Yougov::Surveys::ProfilesController GET:index返回链接到登录用户的所有配置文件,其国家和客户端与链接的调查相同失败/错误:登录用户

RuntimeError:
   Could not find a valid mapping for nil
 # /Users/donovan.thomson/.rvm/gems/ruby-2.2.2@insight-app/gems/devise-2.2.8/lib/devise/mapping.rb:42:in `find_scope!'
 # /Users/donovan.thomson/.rvm/gems/ruby-2.2.2@insight-app/gems/devise-2.2.8/lib/devise/test_helpers.rb:46:in `sign_in'
 # ./spec/support/controller_macros.rb:17:in `block in login_specific_user'

因此,我的控制器的基本框架如下所示:

class ProfilesController < ApplicationController

  def index
    render json: Profile.where(user_id: current_user.id)
  end
end

我假设这意味着用户没有像我期望的那样登录
我的规格如下

require 'spec_helper'

describe ProfilesController, type: :controller do

  before do
    @user = FactoryGirl.create :user
    @profile = FactoryGirl.create :profile, user: @user
    FactoryGirl.create :profile
  end

  describe "GET :index" do

    login_specific_user(@user)

    it "returns all profiles linked to the loged in user with the same country and client as the linked survey" do
      get :index
      expect(response.body).to eq(@profile.to_json)
    end
  end

end

我的控制器宏如下:

module ControllerMacros

  def login_admin
    before :each do
      sign_in ControllerMacros.get_user(@request, :admin, :admin_user)
    end
  end

  def login_user
    before :each do
      sign_in ControllerMacros.get_user(@request, :user)
    end
  end

  def login_specific_user(user)
    before :each do
      sign_in user
    end
  end

  class << self

    def get_user(req, mapping, type=mapping)
      req.env["devise.mapping"] = Devise.mappings[mapping]
      user = FactoryGirl.create(type)
      user.confirm!
      user
    end

  end
end
wqnecbli

wqnecbli1#

我通过不使用控制器宏而只是在before块中添加以下代码来解决这个问题

before do
    @user = FactoryGirl.create :user
    @user.confirm!
    sign_in @user
end
fae0ux8s

fae0ux8s2#

创建spec/support/devise.rb

# frozen_string_literal: true

RSpec.configure do |config|
  config.include Warden::Test::Helpers
end

在spec/rails_helper.rb中包含以下支持文件:

require 'support/devise'

在您的rspec控制器中

# Create user however you want (e.g. using Factory Bot)
user = FactoryBot.create(:user)
login_as(user)

# Session will now be authenticated
visit root_path

相关问题