たろすの技術メモ

Jot Down the Tech

ソフトウェアエンジニアのメモ書き

Punditをテストする

前提

  • Punditの基本的な使い方等については割愛します。
  • rails v7.0.4
  • pundit v2.3.0
  • factory_bot_rails v6.2.0
  • rspec-rails v6.0.1

以下のPolicyをテストします。

# app/policies/hoge_policy.rb

class HogePolicy < ApplicationPolicy
  def show?
    user.admin?
  end

  class Scope < Scope
    def resolve
      scope.all
    end
  end
end

準備

以下を追加します。これでpermitなどのmatchersを使用できるようになります。

# spec/rails_helper.rb
require 'pundit/rspec'

FactoryBot

# spec/factories/user.rb
FactoryBot.define do
  factory :user do
    admin { false }
  end
end

RSpec

# spec/policies/hoge_policy.rb
require 'rails_helper'

RSpec.describe HogePolicy do
  let(:record) { Hoge.new }

  permissions :show? do
    context 'when user is admin' do
      let(:user) { create(:user, admin: true) }

      it 'grants access' do
        expect(described_class).to permit(user, record)
      end
    end

    context 'when user is not admin' do
        let(:user) { create(:user) }
    
      it 'denies access' do
        expect(described_class).not_to permit(user, record)
      end
      end
  end
end

補足

new?など他のアクションも同様にテストしたい場合は以下のようにカンマで続けます。

permissions :show?, :new? do

参考

GitHub - varvet/pundit: Minimal authorization through OO design and pure Ruby classes

Testing Pundit Policies - My Coding Journey