summaryrefslogtreecommitdiff
path: root/spec/support/shared_examples/graphql/spam_protection_shared_examples.rb
blob: 8fb89a4f80ea81800bb897502fe0aab2a5384687 (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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# frozen_string_literal: true

require 'spec_helper'

RSpec.shared_examples 'has spam protection' do
  include AfterNextHelpers

  describe '#check_spam_action_response!' do
    let(:variables) { nil }
    let(:headers) { {} }
    let(:spam_log_id) { 123 }
    let(:captcha_site_key) { 'abc123' }

    def send_request
      post_graphql_mutation(mutation, current_user: current_user)
    end

    before do
      allow_next(mutation_class).to receive(:spam_action_response_fields).and_return(
        spam: spam,
        needs_captcha_response: render_captcha,
        spam_log_id: spam_log_id,
        captcha_site_key: captcha_site_key
      )
    end

    context 'when the object is spam (DISALLOW)' do
      shared_examples 'disallow response' do
        it 'informs the client that the request was denied as spam' do
          send_request

          expect(graphql_errors)
            .to contain_exactly a_hash_including('message' => ::Mutations::SpamProtection::SPAM_DISALLOWED_MESSAGE)
          expect(graphql_errors)
            .to contain_exactly a_hash_including('extensions' => { "spam" => true })
        end
      end

      let(:spam) { true }

      context 'and no CAPTCHA is available' do
        let(:render_captcha) { false }

        it_behaves_like 'disallow response'
      end

      context 'and a CAPTCHA is required' do
        let(:render_captcha) { true }

        it_behaves_like 'disallow response'
      end
    end

    context 'when the object is not spam (CONDITIONAL ALLOW)' do
      let(:spam) { false }

      context 'and no CAPTCHA is required' do
        let(:render_captcha) { false }

        it 'does not return a to-level error' do
          send_request

          expect(graphql_errors).to be_blank
        end
      end

      context 'and a CAPTCHA is required' do
        let(:render_captcha) { true }

        it 'informs the client that the request may be retried after solving the CAPTCHA' do
          send_request

          expect(graphql_errors)
            .to contain_exactly a_hash_including('message' => ::Mutations::SpamProtection::NEEDS_CAPTCHA_RESPONSE_MESSAGE)
          expect(graphql_errors)
            .to contain_exactly a_hash_including('extensions' => {
              "captcha_site_key" => captcha_site_key,
              "needs_captcha_response" => true,
              "spam_log_id" => spam_log_id
            })
        end
      end
    end
  end
end