module Moat::RSpec::PolicyExampleGroup

Public Class Methods

included(base_class) click to toggle source
# File lib/moat/rspec.rb, line 155
def self.included(base_class)
  base_class.metadata[:type] = :policy

  class << base_class
    def roles(*roles, &block)
      roles.each do |role|
        describe(role.to_s, role: role, caller: caller) { instance_eval(&block) }
      end
    end
    alias_method :role, :roles

    def resource(&block)
      fail ArgumentError, "#{__method__} called without a block" unless block
      let(:policy_example_resource) { instance_eval(&block) }
    end

    def scope(&block)
      fail ArgumentError, "#{__method__} called without a block" unless block
      let(:policy_example_scope) { instance_eval(&block) }
    end

    def policy_filters(*filters)
      let(:policy_filters) { filters }
    end

    def policy_authorizations(*authorizations)
      let(:policy_authorizations) { authorizations }
    end
  end

  base_class.class_eval do
    subject { described_class }

    let(:policy_authorizations) do
      fail NotImplementedError, "List of policy_authorizations undefined"
    end

    let(:policy_filters) do
      fail NotImplementedError, "List of policy_filters undefined"
    end

    let(:policy_example_resource) do
      fail NotImplementedError, "A resource has not been defined"
    end

    # a scope that contains at least the resource
    let(:policy_example_scope) do
      if policy_example_resource.class.respond_to?(:all)
        policy_example_resource.class.all
      else
        [policy_example_resource]
      end
    end
  end
end