测试 CanCan 在没有模型的情况下使用 RSpec 查看页面的能力

Testing CanCan ability to view pages with RSpec for controller without a model

我有一个 Rails 应用程序有一个没有 model/object 的控制器来处理报告:

# reports_controller.rb

class ReportsController < ApplicationController

  authorize_resource :class => false

  def index
  end

  def report_title
    # etc.
  end

  # etc.

end

用户对象的角色可以是:admin、normal 或 viewer。管理员可以做任何事情,普通用户有一堆规则,查看者不能对应用程序的任何对象做任何事情,但他们可以查看所有报告。

# ability.rb

def initialize(user)
  if user.admin?
    can :manage, :all

  elsif user.normal?
    # stuff according to business rules...

  elsif user.viewer?
    can [:index, :report_title, ...], :report
  end
end

这按预期工作(因为所有其他控制器都有 load_and_authorize_resource),但是我如何在 ability.rb 中对这些行进行单元测试?我可以在 ability_spec.rb 中使用我的其他单元测试来完成它,还是我必须仅通过请求来测试它?

顺便说一句,通过请求进行测试确实有效,我只是想知道是否可以在这里/也进行测试。

# ability_spec.rb

RSpec.describe User do
  describe "abilities" do
    subject(:ability){ Ability.new(user) }

    CRUD = [:create, :read, :update, :destroy]
    ALL_MODELS = # a list of models

    # ...

    context "a report viewer" do
      let(:user){ FactoryGirl.create(:user, :viewer) }

      it 'cannot do anything with any objects' do
        ALL_MODELS.each do |object|
          CRUD.each do |action|
            should_not be_able_to(action, object)
          end
        end
      end

      it 'can access all the report actions' do
        # ???
      end
    end
  end
end

是的,您应该可以在 ability_spec.rb 中测试该能力。我认为添加以下行可能有效:

it 'can access all the report actions' do
  should be_able_to :index, ReportsController
  should be_able_to :report_title, ReportsController
end

如果您设置 authorize_resource :class => ReportsController 而不是 false 并使用 can [:index, :report_title, ...], :ReportsController 而不是符号 :report

我还没有尝试过,如果有效请告诉我。