Update tests for admin flag

This commit is contained in:
Eugene Burmakin 2024-07-19 20:37:57 +02:00
parent 66ff0c3bed
commit 2d2eeda9e7
5 changed files with 95 additions and 60 deletions

View file

@ -11,7 +11,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
### Added
- Admin flag to the database.
- Admin flag to the database. Now not only the first user in the system can create new users, but also users with the admin flag set to true. This will make easier introduction of more admin functions in the future.
### Fixed

View file

@ -16,7 +16,7 @@ class ApplicationController < ActionController::Base
def authenticate_admin!
return if current_user.admin?
redirect_to root_path, notice: 'You are not authorized to perform this action.', status: :unauthorized
redirect_to root_path, notice: 'You are not authorized to perform this action.', status: :see_other
end
def authenticate_api_key

View file

@ -1,3 +1,5 @@
# frozen_string_literal: true
FactoryBot.define do
factory :user do
sequence :email do |n|
@ -5,5 +7,9 @@ FactoryBot.define do
end
password { SecureRandom.hex(8) }
trait :admin do
admin { true }
end
end
end

View file

@ -17,11 +17,19 @@ RSpec.describe '/settings/background_jobs', type: :request do
end
context 'when user is authenticated' do
let(:user) { create(:user) }
before { sign_in create(:user) }
before do
sign_in user
context 'when user is not an admin' do
it 'redirects to root page' do
get settings_background_jobs_url
expect(response).to redirect_to(root_url)
expect(flash[:notice]).to eq('You are not authorized to perform this action.')
end
end
context 'when user is an admin' do
before { sign_in create(:user, :admin) }
describe 'GET /index' do
it 'renders a successful response' do
@ -67,3 +75,4 @@ RSpec.describe '/settings/background_jobs', type: :request do
end
end
end
end

View file

@ -3,14 +3,32 @@
require 'rails_helper'
RSpec.describe '/settings/users', type: :request do
before do
sign_in create(:user)
let(:valid_attributes) { { email: 'user@domain.com' } }
context 'when user is not authenticated' do
it 'redirects to sign in page' do
post settings_users_url, params: { user: valid_attributes }
expect(response).to redirect_to(new_user_session_url)
end
end
context 'when user is authenticated' do
context 'when user is not an admin' do
before { sign_in create(:user) }
it 'redirects to root page' do
post settings_users_url, params: { user: valid_attributes }
expect(response).to redirect_to(root_url)
end
end
context 'when user is an admin' do
before { sign_in create(:user, :admin) }
describe 'POST /create' do
context 'with valid parameters' do
let(:valid_attributes) { { email: 'user@domain.com' } }
it 'creates a new User' do
expect do
post settings_users_url, params: { user: valid_attributes }
@ -42,3 +60,5 @@ RSpec.describe '/settings/users', type: :request do
end
end
end
end
end