2

Rails: 4.2 Pundit: 1.0.1

What's the strategy for testing headless policies? When I use the DSL given in the README examples, I run into issues with scoping.

The AdminPolicy:

class AdminPolicy < ApplicationPolicy

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

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

The 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

The error output:

  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)
Michael Lang
  • 1,028
  • 12
  • 21

1 Answers1

0

After posting the question, realized how #scope was getting called in the first place.

The permissions block was defined with :show? and should be defined with :manage_any? which is the context I really wanted to test. As a consequence, I was actually calling :show? from the ApplicationPolicy which was invoking the scope.

resource likewise is not needed in this headless context, so eliminate that. We're left with the following:

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
Michael Lang
  • 1,028
  • 12
  • 21