about summary refs log tree commit diff
path: root/spec/controllers/api/base_controller_spec.rb
blob: 750ccc8cf67235865fa2790eec50794990640618 (plain) (blame)
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
# frozen_string_literal: true

require 'rails_helper'

class FakeService; end

describe Api::BaseController do
  controller do
    def success
      head 200
    end

    def error
      FakeService.new
    end
  end

  describe 'Forgery protection' do
    before do
      routes.draw { post 'success' => 'api/base#success' }
    end

    it 'does not protect from forgery' do
      ActionController::Base.allow_forgery_protection = true
      post 'success'
      expect(response).to have_http_status(200)
    end
  end

  describe 'Error handling' do
    ERRORS_WITH_CODES = {
      ActiveRecord::RecordInvalid => 422,
      Mastodon::ValidationError => 422,
      ActiveRecord::RecordNotFound => 404,
      Mastodon::UnexpectedResponseError => 503,
      HTTP::Error => 503,
      OpenSSL::SSL::SSLError => 503,
      Mastodon::NotPermittedError => 403,
    }

    before do
      routes.draw { get 'error' => 'api/base#error' }
    end

    ERRORS_WITH_CODES.each do |error, code|
      it "Handles error class of #{error}" do
        expect(FakeService).to receive(:new).and_raise(error)

        get 'error'
        expect(response).to have_http_status(code)
      end
    end
  end
end