Is this RSpec spec actually proving that my Pundit Policy is restricting access to the show action?

383 views Asked by At

I'm struggling to understand Pundit generally, but specifically how to test it. I've gotten my test to pass by ignoring some things from examples online that seemed to have no effect on what I was doing or didn't seem to be having the right info passed to it. Now I'm not sure the thing I did is actually proving that my Policy is working or whether I've bypassed the test.

I'm testing that a visitor who tries to access someone's gallery does not have access to it. In the event that a visitor would type in http://localhost:3000/galleries/1 to the browser they wouldn't get access. This does happen in practice, the visitor is redirected to the sign in page, but I'm trying to learn how to do testing using RSpec and Pundit, so I can use the tools with confidence and accuracy.

A little help is appreciated. Below is what I believe to be the important code:

gallery_policy_spec.rb

RSpec.describe GalleryPolicy do
  #Pretty sure I skipped over subject because I kept getting errors 
  #saying user and gallery were undefined variables
  subject { GalleryPolicy.new(user, gallery) }  

  context "for a vistor" do #passes I know why
    it "has(gallery) a valid factory" do
      expect(FactoryGirl.build(:gallery)).to be_valid
    end

    it 'has(user) a valid factory' do #passes I know why
      expect(FactoryGirl.build(:user)).to be_valid
    end

    permissions :show? do #passes but I don't know why
      it "denies access to show if visitor" do
        expect(GalleryPolicy).not_to permit(FactoryGirl.build(:user, id: nil), FactoryGirl.create(:gallery))
      end
    end
  end
end

gallery_policy.rb

class GalleryPolicy < ApplicationPolicy
  attr_reader :user, :model

  def initialize(user, model)
    @user = user
    @gallery = model
  end

  class Scope < Scope
    def resolve
        scope.where(:user_id == user.id)
    end
  end

  def show?
    @gallery.user == @user
  end

  def new?
    create?
  end

  def new?
    true
  end
end

application_policy.rb I think this is standard, but I didn't want to leave out valuable info

class ApplicationPolicy
  attr_reader :user, :record

  def initialize(user, record)
    raise Pundit::NotAuthorizedError, "must be logged in" unless user
    @user = user
    @record = record
  end

  def index?
    false
  end

  def show?
    false
  end

  def create?
    false
  end

  def new?
    create?
  end

  def update?
    false
  end

  def edit?
    update?
  end

  def destroy?
    false
  end

  class Scope
    attr_reader :user, :scope

    def initialize(user, scope)
      @user = user
      @scope = scope
    end

    def resolve
      scope
    end
  end
end

gallery.rb #factory

FactoryGirl.define do
  factory :gallery do
    title { Faker::Book.title }
    association :user
  end
end
0

There are 0 answers