测试管理员授权

时间:2015-04-08 18:31:23

标签: ruby-on-rails authentication rspec admin factory-bot

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

  1) Admin::DashboardController GET index with correct credentials returns http success
     Failure/Error: get :index
     NoMethodError:
       undefined method `admin?' for nil:NilClass

阅读源于同一错误的问题。它似乎可能current_user实际上返回nil,但是当我尝试将current_user的会话设置为user变量时,我仍然得到相同的错误。我也尝试对current_user进行存根,但仍然遇到同样的错误。

以下是规范:

dashboard_controller_spec.rb

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

class Admin::DashboardController < ApplicationController
    before_action :require_admin
    before_action :require_auth

  def index
  end
end

application_controller.rb

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

1 个答案:

答案 0 :(得分:0)

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

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仅在浏览器发送有关referrer的信息时才有效,但并非总是如此。即隐私模式下的firefox没有。

相关问题