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

时间:2019-02-22 15:39:14

标签: ruby-on-rails cancan cancancan

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

我刚开始很简单,所以这个控制器还没有什么 controllers / 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: 'test@test.com', 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调用,针对用户的第三个测试也没有问题通过。

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

谢谢!

1 个答案:

答案 0 :(得分:1)

我的理解是没有别名为:access 的操作,引用了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