Rails CanCanCan能力问题与无模型控制器

问题描述 投票:0回答:1

我有一个简单的控制器方法:WelcomeController#dashboard,它是用户登录后的登陆页面(用户具有此测试的“经理”角色)。

我开始很简单,所以这个控制器还没有多少控制器/ welcome_controller.rb:

class WelcomeController < ApplicationController
  skip_authorize_resource only: :index
  authorize_resource class: false, only: [:dashboard]

  skip_before_action :authenticate_user!, only: [:index]
  layout 'external', only: [:index]

  def index; end

  def dashboard; end
end

所以,我已经安装了CanCanCan并且在我的models / ability.rb文件中:

class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new # guest user (not logged in)
    if user.admin?
      can :manage, :all
      can :access, :rails_admin
    elsif user.manager?
      can :read, Lesson
      can :access, :dashboard
      can :modify, Company
    elsif user.user?
      can :read, Lesson
    else
      can :read, :root
    end
  end
end

但是,我的Rspec测试失败了,我无法弄清楚原因。 spec / controllers / welcome_controller_spec.rb中的代码是:

require 'rails_helper'
require 'cancan/matchers'

RSpec.describe WelcomeController, type: :controller do
  describe 'GET #index' do
    it 'returns http success' do
      get :index
      expect(response).to have_http_status(:success)
    end
  end

  describe 'GET #dashboard' do
    it 'manager routes to dashboard after login' do
      company = Company.create!(name: 'ACME', domain: 'acme.com')
      user = User.create!(email: '[email protected]', password: 'password', password_confirmation: 'password', company_id: company.id, role: 1)
      sign_in user
      get :dashboard
      expect(response).to have_http_status(:success)
    end

    it 'user does not route to dashboard after login' do
      user = create(:user)
      sign_in user
      expect { get :dashboard }.to raise_error(CanCan::AccessDenied)
    end
  end
end

导致此错误:

Failures:

  1) WelcomeController GET #dashboard manager routes to dashboard after login
     Failure/Error: get :dashboard

     CanCan::AccessDenied:
       You are not authorized to access this page.
     # ./spec/controllers/welcome_controller_spec.rb:17:in `block (3 levels) in <top (required)>'

我觉得有趣的是,只有“登录后经理路由到仪表板”测试失败了,因为即使我使用相同的:dashboard调用,用户的第3次测试也没有问题。

如有任何帮助/建议,我将不胜感激。

谢谢!

ruby-on-rails cancan cancancan
1个回答
1
投票

我理解alias_action名称没有动作:访问,引用from this link(如果不正确,请纠正我),但你可以用alias_action创建自定义动作

你的能力.rb

class Ability
  include CanCan::Ability

  def initialize(user)
    # here you create alias_action
    alias_action :create, :read, :update, :destroy, to: :access
    user ||= User.new # guest user (not logged in)
    if user.admin?
      can :manage, :all
      can :access, :rails_admin
    elsif user.manager?
      can :read, Lesson
      can :access, :dashboard
      can :modify, Company
    elsif user.user?
      can :read, Lesson
    else
      can :read, :root
    end
  end
end
© www.soinside.com 2019 - 2024. All rights reserved.