Module: ActionPolicy::TestHelper

Defined in:
lib/action_policy/test_helper.rb

Overview

Provides assertions for policies usage

Instance Method Summary collapse

Instance Method Details

#assert_authorized_to(rule, target, with: nil) ⇒ Object

Asserts that the given policy was used to authorize the given target.

def test_authorize
  assert_authorized_to(:show?, user, with: UserPolicy) do
    get :show, id: user.id
  end
end

You can omit the policy (then it would be inferred from the target):

assert_authorized_to(:show?, user) do
  get :show, id: user.id
end

rubocop: disable Metrics/MethodLength

Raises:

  • (ArgumentError)


23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/action_policy/test_helper.rb', line 23

def assert_authorized_to(rule, target, with: nil)
  raise ArgumentError, "Block is required" unless block_given?

  policy = with || ::ActionPolicy.lookup(target)

  begin
    ActionPolicy::Testing::AuthorizeTracker.tracking { yield }
  rescue ActionPolicy::Unauthorized # rubocop: disable Lint/HandleExceptions
    # we don't want to care about authorization result
  end

  actual_calls = ActionPolicy::Testing::AuthorizeTracker.calls

  assert(
    actual_calls.any? { |call| call.matches?(policy, rule, target) },
    "Expected #{target.inspect} to be authorized with #{policy}##{rule}, " \
    "but no such authorization has been made.\n" \
    "Registered authorizations: " \
    "#{actual_calls.empty? ? 'none' : actual_calls.map(&:inspect).join(',')}"
  )
end