sajad torkamani

Setup

Add the following to your rails_helper.rb:

require 'pundit/rspec'

Example spec

Let’s suppose we have a QuotePolicy that should only allow the owner/creator of a quote to edit the quote. We might write a spec at spec/policies/quote_policy_spec.rb that looks like this:

# frozen_string_literal: true

require 'rails_helper'

RSpec.describe QuotePolicy, type: :policy do
  subject(:policy) { described_class }

  let(:user) { create(:user) }
  let(:quote) { create(:quote) }

  permissions :edit?, :update? do
    it 'denies permission if user is not the owner of the quote' do
      expect(policy).not_to permit(user, quote)
    end

    it 'grants permission if user is the owner of the quote' do
      quote = create(:quote, user:)
      expect(policy).to permit(user, quote)
    end
  end

  permissions :destroy? do
    it 'denies permission if user is not the owner of the quote' do
      expect(policy).not_to permit(user, quote)
    end

    it 'grants permission if user is the owner of the quote' do
      quote = create(:quote, user: user)
      expect(policy).to permit(user, quote)
    end
  end
end

Leave a comment

Your email address will not be published. Required fields are marked *