【发布时间】:2023-03-20 19:10:01
【问题描述】:
我正在学习 Rails 4 In Action 教程,并且我正在学习第 7 章。
这是我看到的错误:
± bundle exec rspec
.F........................
Failures:
1) Admin::UsersController GET #index returns http success
Failure/Error: get :index
NoMethodError:
undefined method `authenticate!' for nil:NilClass
# ./app/controllers/admin/application_controller.rb:10:in `authorize_admin!'
# ./spec/controllers/admin/users_controller_spec.rb:7:in `block (3 levels) in <top (required)>'
Finished in 1.2 seconds (files took 1.86 seconds to load)
26 examples, 1 failure
Failed examples:
rspec ./spec/controllers/admin/users_controller_spec.rb:6 # Admin::UsersController GET #index returns http success
./app/controllers/admin/application_controller.rb 看起来像这样:
class Admin::ApplicationController < ApplicationController
before_action :authorize_admin!
def index
end
private
def authorize_admin!
authenticate_user!
unless current_user.admin?
redirect_to root_path, alert: "You must be an admin to do that."
end
end
end
./app/controllers/admin/users_controller.rb 看起来像这样:
class Admin::UsersController < Admin::ApplicationController
def index
@users = User.order(:email)
end
def new
@user = User.new
end
def create
@user = User.new(user_params)
if @user.save
flash[:notice] = "User has been created."
redirect_to admin_users_path
else
flash.now[:alert] = "User has not been created."
render "new"
end
end
private
def user_params
params.require(:user).permit(:email, :password)
end
end
./spec/controllers/admin/users_controller_spec.rb 看起来像这样:
require 'rails_helper'
RSpec.describe Admin::UsersController, type: :controller do
describe "GET #index" do
it "returns http success" do
get :index
expect(response).to have_http_status(:success)
end
end
end
您可能会告诉我有点超出我的深度,任何解决此问题的帮助将不胜感激。
【问题讨论】:
-
我相信
authenticate_user!来自 Devise 旗下的 Warden?
标签: ruby ruby-on-rails-4 rspec devise capybara