Welcome to mirror list, hosted at ThFree Co, Russian Federation.

access_matchers_for_request.rb « matchers « support « spec - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 9b80bf8562c24ac2d4bc0a9fac2f1feeddd8f2b1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# frozen_string_literal: true

# AccessMatchersForRequest
#
# Matchers to test the access permissions for requests specs (most useful for API tests).
module AccessMatchersForRequest
  extend RSpec::Matchers::DSL
  include AccessMatchersHelpers

  EXPECTED_STATUS_CODES_ALLOWED = [200, 201, 204, 302, 304].freeze
  EXPECTED_STATUS_CODES_DENIED = [401, 403, 404].freeze

  def description_for(role, type, expected, result)
    "be #{type} for #{role} role. Expected status code: any of #{expected.join(', ')} Got: #{result}"
  end

  matcher :be_allowed_for do |role|
    match do |action|
      # methods called in this and negated block are being run in context of ExampleGroup
      # (not matcher) instance so we have to pass data via local vars

      run_matcher(action, role, @membership, @owned_objects)

      EXPECTED_STATUS_CODES_ALLOWED.include?(response.status)
    end

    match_when_negated do |action|
      run_matcher(action, role, @membership, @owned_objects)

      EXPECTED_STATUS_CODES_DENIED.include?(response.status)
    end

    chain :of do |membership|
      @membership = membership
    end

    chain :own do |*owned_objects|
      @owned_objects = owned_objects
    end

    failure_message do
      "expected this action to #{description_for(role, 'allowed', EXPECTED_STATUS_CODES_ALLOWED, response.status)}"
    end

    failure_message_when_negated do
      "expected this action to #{description_for(role, 'denied', EXPECTED_STATUS_CODES_DENIED, response.status)}"
    end

    supports_block_expectations
  end

  RSpec::Matchers.define_negated_matcher :be_denied_for, :be_allowed_for
end