首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >测试管理授权

测试管理授权
EN

Stack Overflow用户
提问于 2015-04-08 18:31:23
回答 1查看 261关注 0票数 0

身份验证完全是从零开始的,目标是在我完成时测试所有的东西。我创建了一个只有管理员才能访问的管理仪表板,但是我的测试给了我以下错误:

代码语言:javascript
复制
  1) Admin::DashboardController GET index with correct credentials returns http success
     Failure/Error: get :index
     NoMethodError:
       undefined method `admin?' for nil:NilClass

从阅读同样的错误产生的问题。看起来,实际上返回零的可能是current_user,但是当我试图将当前_user的会话设置为user变量时,仍然会得到相同的错误。我还尝试过在current_user中添加根,但仍然得到了相同的错误。

这是规范:

dashboard_controller_spec.rb

代码语言:javascript
复制
describe "GET index" do
    before(:each) do
        allow(controller).to receive(:require_auth)
        allow(controller).to receive(:current_user)
end

context "with correct credentials" do
    it "returns http success" do
      user = create(:admin)
      session[user_id: user]
      get :index 
      expect(response).to have_http_status(:success)
    end
end

dashboard_controller.rb

代码语言:javascript
复制
class Admin::DashboardController < ApplicationController
    before_action :require_admin
    before_action :require_auth

  def index
  end
end

application_controller.rb

代码语言:javascript
复制
class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  add_flash_types :success, :error

  private
  helper_method :current_user
  helper_method :logged_in?

  def logged_in?
    current_user
  end

  def current_user
    @current_user ||= User.find(session[:user_id]) if session[:user_id]
    rescue ActiveRecord::RecordNotFound
  end

  def require_auth
    unless current_user
      session[:target] = request.fullpath
      redirect_to new_user_session_path, 
        notice: "You must be logged in to access that page."
    end
  end

  def require_admin
    unless current_user.admin?
      redirect_to :back, 
        notice: "Access denied."
    end
  end
end
EN

回答 1

Stack Overflow用户

发布于 2015-04-08 19:17:22

也许您应该在会话中存储user.id而不是用户:

代码语言:javascript
复制
context "with correct credentials" do
it "returns http success" do
  user = create(:admin)
  get :index, nil, {user_id: user.id}
  expect(response).to have_http_status(:success)
end
end

另外,顺便指出的是,redirect_to :back只在浏览器发送有关引用程序的信息时才能工作,但并不总是正确的。也就是说,隐私模式下的firefox没有。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29522637

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档