如何测试Pundit无头政策?

时间:2016-03-22 03:29:17

标签: ruby-on-rails ruby-on-rails-4 pundit

Rails:4.2 专家:1.0.1

测试无头政策的策略是什么?当我使用README示例中给出的DSL时,我遇到了范围界定问题。

AdminPolicy:

class AdminPolicy < ApplicationPolicy

  def initialize user, resource
    @user = user
    @resource = resource
  end

  def manage_any?
    user.present? && user.system_admin_role?
  end
end

rspec:

require 'rails_helper'

describe AdminPolicy do

  subject { described_class }

  context "limited_user" do
    let(:user)     { create :user }
    let(:resource) { nil }

    permissions :show? do
      it { is_expected.to_not permit :manage_any?, resource }
    end
  end

end

错误输出:

  1) AdminPolicy limited_user show? should not permit #<User id: 2380, email: "first1.last1@test.gov", [...], system_admin_role: false> and :manage_any?
     Failure/Error: scope.where(id: resource.id).exists?

     NameError:
       undefined local variable or method `scope' for #<AdminPolicy:0x007fae12e2f618>
     # ./app/policies/application_policy.rb:25:in `show?'
     # /Users/mwlang/.rvm/gems/ruby-2.1.5/gems/pundit-1.0.1/lib/pundit/rspec.rb:15:in `public_send'
     # /Users/mwlang/.rvm/gems/ruby-2.1.5/gems/pundit-1.0.1/lib/pundit/rspec.rb:15:in `block (3 levels) in <module:Matchers>'
     # /Users/mwlang/.rvm/gems/ruby-2.1.5/gems/pundit-1.0.1/lib/pundit/rspec.rb:15:in `each'
     # /Users/mwlang/.rvm/gems/ruby-2.1.5/gems/pundit-1.0.1/lib/pundit/rspec.rb:15:in `find_all'
     # /Users/mwlang/.rvm/gems/ruby-2.1.5/gems/pundit-1.0.1/lib/pundit/rspec.rb:15:in `block (2 levels) in <module:Matchers>'
     # ./spec/policies/admin_policy_spec.rb:13:in `block (4 levels) in <top (required)>'

Finished in 0.41901 seconds (files took 2.02 seconds to load)

1 个答案:

答案 0 :(得分:0)

在发布问题后,意识到首先是如何调用#scope。

permissions块定义为:show?,应使用:manage_any?定义,这是我真正想要测试的上下文。因此,我实际上是在调用范围的ApplicationPolicy中调用:show?

在这无头的情境中同样不需要

resource,所以要消除它。我们留下以下内容:

require 'rails_helper'

describe AdminPolicy do

  subject { described_class }

  context "limited_user" do
    let(:user)          { create :user }
    let(:system_admin)  { create :user, system_admin_role: true }

    permissions :manage_any? do
      it { is_expected.to_not permit user }
      it { is_expected.to     permit system_admin }
    end
  end
end