【发布时间】:2015-06-13 21:10:57
【问题描述】:
身份验证完全是从头开始,目标是在我使用它的同时测试所有内容。我创建了一个只有管理员才能访问的管理仪表板,但我的测试给了我以下错误:
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
【问题讨论】:
-
如果您使用的是 Devise,它会为您提供可用于在控制器中登录和注销的助手。 test helpers
-
我正在从头开始构建我的身份验证,作为身份验证/授权如何工作以及 TDD/BDD 的学习经验。
标签: ruby-on-rails authentication rspec admin factory-bot