1

I am using Pundit for authorization in my application with rspec for testing.

require 'rails_helper'

describe SubjectPolicy do
  subject { described_class.new(user, subject) }
  let(:subject) { Subject.create }

  context 'is an administrator' do
    let(:role) { Role.create(role_name: 'admin') }
    let(:user) { User.create(role_id: role.id) }

    it { is_expected.to permit_actions([:index]) }
  end

  context 'is a teacher' do
    let(:role) { Role.create(role_name: 'teacher') }
    let(:user) { User.create(role_id: role.id) }

    it { is_expected.to forbid_actions([:index]) }
  end
end

When running the test for this spec test I receive the following error.

Failure/Error: it { is_expected.to permit_actions([:index]) }

NoMethodError: undefined method 'index?' for #<Subject:0x007fdcc1f70fd0>

There is a route for this index action and it is in my subjects_controller.

The code in the subject policy is very simple.

class SubjectPolicy < ApplicationPolicy
  def index?
    @user.is_admin?
  end
end

Here is the index action in my subjects_controller

def index
  @subjects = Subject.all
  authorize @subjects
end

I am able to create subjects as an admin, and it does in fact block non-admins from accessing the index. But I am confused as to why this test would fail. I have this policy spec set up just like others and they are passing just fine. Any idea?

Trenton Tyler
  • 1,692
  • 3
  • 24
  • 53
  • `subject { described_class.new(user, subject) }` OR `let(:subject) { Subject.create }` which of these is the real subject? – Taryn East Apr 05 '18 at 04:20
  • `let(:subject) { Subject.create }` is the real object. – Trenton Tyler Apr 05 '18 at 04:24
  • 1
    Then you need to get rid of the other one... my point was it might be getting confused about which is which ;) – Taryn East Apr 05 '18 at 05:08
  • 1
    Pundit-matchers, a gem I am using to test pundit with rspec, requires the `described_class` to map the objects to the pundit policy. – Trenton Tyler Apr 05 '18 at 17:30
  • Great, so rename one or delete one... whichever it is you need to do to get it to work... either way there are two named the same and it's confusing which one will be used by what code :) – Taryn East Apr 05 '18 at 23:16

0 Answers0