身份验证完全是从零开始的,目标是在我完成时测试所有的东西。我创建了一个只有管理员才能访问的管理仪表板,但是我的测试给了我以下错误:
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
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
enddashboard_controller.rb
class Admin::DashboardController < ApplicationController
before_action :require_admin
before_action :require_auth
def index
end
endapplication_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发布于 2015-04-08 19:17:22
也许您应该在会话中存储user.id而不是用户:
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没有。
https://stackoverflow.com/questions/29522637
复制相似问题