看来,该设计的 sign_in 助手不起作用。
常规登录过程作为一种魅力,通过集成测试和手动填写登录表单进行测试。两种方法都为 current_user 提供了正确的值。
我想测试用户配置文件的编辑控制器功能并遇到“未授权”问题。这让我看到了当前的规范,我只是想批准实际上没有用户登录,因此 current_user 为 nil。
我想,我的代码中只是有一些错误。
你有什么提示可以解决我的问题吗?
我正在使用Rails 5.2和ruby 2.5.0
模型/用户.rb
class User < ApplicationRecord
enum role: [:registered, :editor, :admin]
after_initialize :set_default_role, if: :new_record?
def set_default_role
self.role ||= :registered
end
# Include default devise modules. Others available are:
devise :invitable, :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
控制器/application_controller.rb
class ApplicationController < ActionController::Base
before_action :authenticate_user!
before_action :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up, keys: [:first_name, :last_name, :approved])
end
end
控制器/registration_controller.rb
class RegistrationsController < Devise::RegistrationsController
private
def after_inactive_sign_up_path_for(resource)
show_post_register_info_path
end
end
配置/路由.rb
Rails.application.routes.draw do
devise_for :users, controllers: { registrations: 'registrations'}
root to: 'welcome#home
get 'show_post_register_info', to: 'static_pages#show_post_register_info'
end
规格/rails_heper.rb
require 'rspec/rails'
require 'devise'
Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
RSpec.configure do |config|
config.include Devise::Test::ControllerHelpers, type: :controller
config.include Devise::Test::ControllerHelpers, type: :view
config.include Devise::Test::IntegrationHelpers
config.extend ControllerMacros, type: :controller
...
end
支持/controller_macros.rb
module ControllerMacros
def login_user
before(:each) do
@request.env["devise.mapping"] = Devise.mappings[:user]
user = FactoryBot.create(:user)
sign_in user
end
end
end
最后是我的controller_spec:
require 'rails_helper'
RSpec.describe RegistrationsController, type: :controller do
describe 'registrations#update' do
context 'signing in a registered user' do
login_user
it 'should have a current_user' do
expect(subject.current_user).to_not eq(nil)
end
it 'should be signed in' do
expect(subject.user_signed_in?).to be true
end
end
end
end
结果:
1) RegistrationsController registrations#update as a registered user changes the password
Failure/Error: expect(subject.user_signed_in?).to be true
expected true
got false
2) RegistrationsController registrations#update as a registered user should have a current_user
Failure/Error: expect(subject.current_user).to_not eq(nil)
expected: value != nil
got: nil