mastodon/spec/controllers/api/base_controller_spec.rb
Claire e38fc319dc
Refactor and improve tests (#17386)
* Change account and user fabricators to simplify and improve tests

- `Fabricate(:account)` implicitly fabricates an associated `user` if
  no `domain` attribute is given (an account with `domain: nil` is
  considered a local account, but no user record was created), unless
  `user: nil` is passed
- `Fabricate(:account, user: Fabricate(:user))` should still be possible
  but is discouraged.

* Fix and refactor tests

- avoid passing unneeded attributes to `Fabricate(:user)` or
  `Fabricate(:account)`
- avoid embedding `Fabricate(:user)` into a `Fabricate(:account)` or the other
  way around
- prefer `Fabricate(:user, account_attributes: …)` to
  `Fabricate(:user, account: Fabricate(:account, …)`
- also, some tests were using remote accounts with local user records, which is
  not representative of production code.
2022-01-28 00:46:42 +01:00

92 lines
2.2 KiB
Ruby

# 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 'non-functional accounts handling' do
let(:user) { Fabricate(:user) }
let(:token) { Fabricate(:accessible_access_token, resource_owner_id: user.id, scopes: 'read') }
controller do
before_action :require_user!
end
before do
routes.draw { post 'success' => 'api/base#success' }
allow(controller).to receive(:doorkeeper_token) { token }
end
it 'returns http forbidden for unconfirmed accounts' do
user.update(confirmed_at: nil)
post 'success'
expect(response).to have_http_status(403)
end
it 'returns http forbidden for pending accounts' do
user.update(approved: false)
post 'success'
expect(response).to have_http_status(403)
end
it 'returns http forbidden for disabled accounts' do
user.update(disabled: true)
post 'success'
expect(response).to have_http_status(403)
end
it 'returns http forbidden for suspended accounts' do
user.account.suspend!
post 'success'
expect(response).to have_http_status(403)
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