使用RSpec以特定用户身份登录

时间:2016-07-18 12:13:36

标签: ruby-on-rails ruby rspec devise

我试图指出以下内容。

我需要返回链接到登录用户的所有实体。随后我需要在事实之前创建用户,然后确保特定用户已登录。我正在努力通过控制器宏实现此目的。我的规格失败如下

1)Yougov :: Surveys :: ProfilesController GET:index返回链接到loged in user的所有配置文件,其中包含与链接调查相同的国家和客户      失败/错误:sign_in用户

 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

1 个答案:

答案 0 :(得分:0)

我通过不使用控制器宏来解决这个问题,只是将以下内容添加到我之前的块

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