[英]Login as a specific user with RSpec
I am trying to spec the following. 我正在尝试说明以下内容。
I need to return all entities that are linked to the logged in user. 我需要返回链接到已登录用户的所有实体。 Subsequently I need to create the user before the fact and then ensure that the specific user is logged in. I am struggling to achieve this with controller macros. 随后,我需要在事实之前创建用户,然后确保特定用户已登录。我正在努力通过控制器宏来实现这一点。 My specs are failing as follows 我的规格失败如下
1) Yougov::Surveys::ProfilesController GET :index returns all profiles linked to the loged in user with the same country and client as the linked survey Failure/Error: sign_in user 1)Yougov :: Surveys :: ProfilesController GET:index返回与已登录用户链接的所有配置文件,这些用户具有与链接的调查相同的国家和客户失败/错误: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'
So a basic scaffolding of my controller looks as follows : 因此,控制器的基本结构如下所示:
class ProfilesController < ApplicationController
def index
render json: Profile.where(user_id: current_user.id)
end
end
I assume this means the user is not being logged in as I would expect 我认为这意味着用户未按我期望的那样登录
My spec is as follows 我的规格如下
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
My controller macro's are as follows: 我的控制器宏如下:
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
I solved this by not using controller macros and just adding the following to my before block 我不使用控制器宏,而是将以下内容添加到我的before块中来解决了此问题
before do
@user = FactoryGirl.create :user
@user.confirm!
sign_in @user
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.