我遵循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
你可能会告诉我一点点我的深度,任何解决这个问题的帮助都会非常感激。
答案 0 :(得分:0)
您是否设置了使用Devise的rspec?
尝试将以下内容添加到spec / rails_helper.rb
# note: require 'devise' after require 'rspec/rails'
require 'devise'
RSpec.configure do |config|
#...
config.include Devise::Test::ControllerHelpers, :type => :controller
#...
end
答案 1 :(得分:0)
使用RSpec,您可以将以下内容放在名为spec
的文件中或this.spec = spec;
中(或spec/support/devise.rb
如果您使用spec/spec_helper.rb
):
spec/rails_helper.rb
请确保在require rspec-rails
指令之后进行此包含。