AuthorizationAdapter
を継承して独自の authorized?
を作成した時のテストの書き方です。
controller spec
を利用する手もあると思いますが、controller spec
を 使わずに authorized?
だけに焦点を当ててテストを作ることも可能なようです。
テスト対象コード
ActiveAdmin Documentation の Authorization Adapter に記載されている以下の authorized?
に対する spec の書き方を記載します。
app/models/only_authors_authorization.rb
class OnlyAuthorsAuthorization < ActiveAdmin::AuthorizationAdapter
def authorized?(action, subject = nil)
case subject
when normalized(Post)
# 投稿者以外は更新や削除は出来ない
if action == :update || action == :destroy
subject.author == user
else
true
end
else
true
end
end
end
spec の書き方
spec/models/only_authors_authorization_spec.rb
require 'rails_helper'
RSpec.describe OnlyAuthorsAuthorization do
let!(:application) { ActiveAdmin.application }
let!(:namespace) { application.namespaces.first }
let!(:resources) { namespace.resources }
let(:resource) { resources[klass] }
let(:auth) { MyAuthorization.new resource, current_user }
# ログイン中のユーザ
let(:current_user) { FactoryGirl.build(:user) }
describe 'Post' do
let(:klass) { Post }
let(:subject) { post || klass }
describe '投稿者がログイン中' do
let(:post) { FactoryGirl.build(:post, author: current_user) }
it 'index' do
post = nil
expected(auth.authorized?(:read, subject)).to be true
end
it 'show' do
expected(auth.authorized?(:read, subject)).to be true
end
it 'edit' do
expected(auth.authorized?(:update, subject)).to be true
end
it 'destroy' do
expected(auth.authorized?(:destroy, subject)).to be true
end
end
describe '別のユーザがログイン中' do
let(:ohter_user) { FactoryGirl.build(:user) }
let(:post) { FactoryGirl.build(:post, author: ohter_user) }
it 'index' do
post = nil
expected(auth.authorized?(:read, subject)).to be true
end
it 'show' do
expected(auth.authorized?(:read, subject)).to be true
end
it 'edit' do
expected(auth.authorized?(:update, subject)).to be false
end
it 'destroy' do
expected(auth.authorized?(:destroy, subject)).to be false
end
end
end
end