Skip to content

Instantly share code, notes, and snippets.

@alexbrahastoll
Last active August 29, 2015 14:07
Show Gist options
  • Save alexbrahastoll/fba636cbf84cefd2a35d to your computer and use it in GitHub Desktop.
Save alexbrahastoll/fba636cbf84cefd2a35d to your computer and use it in GitHub Desktop.
É esse um uso adequado do fail do RSpec? Abaixo, uma simplificação de uma classe responsável por realizar a autorização de usuários (de acordo com perfis) e a sua respectiva especificação de modelo. Na especificação, o fail é usado para garantir que haja sincronia entre as regras da classe e as regras configuradas na especificação. Outras crític…
# authorizer.rb
class Authorizer
attr_reader :access_granted
def self.allowed_actions_per_role
{
'redacao' => [
'items#new',
'items#edit',
'items#create',
'items#update',
'items#destroy',
'items#update_header',
'menus#show',
'menus#upload_to_s3',
'menus#reposition',
'menus#update_header',
'controller#action_not_present_in_the_specs'
]
}
end
def initialize(user, controller_action)
@user = user
@controller_action = controller_action
@access_granted = authorized?
end
private
def authorized?
if Authorizer.allowed_actions_per_role.fetch(@user.role).include?(@controller_action)
true
else
false
end
end
end
# authorizer_spec.rb
require 'rails_helper'
RSpec.describe Authorizer, type: :model do
let(:redacao_user) { create(:user) }
let(:redacao_actions) {
[
'items#new',
'items#edit',
'items#create',
'items#update',
'items#destroy',
'items#update_header',
'menus#show',
'menus#upload_to_s3',
'menus#reposition',
'menus#update_header'
]
}
it 'should allow an user with the redacao role to access the redacao actions' do
check_if_rules_are_synced! do
redacao_actions == Authorizer.allowed_actions_per_role.fetch('redacao')
end
# Provavelmente, o uso de expect seria melhor, mas só tive essa ideia após o uso do fail
# expect(redacao_actions).to eq(Authorizer.allowed_actions_per_role.fetch('redacao'))
redacao_actions.each do |action|
expect(Authorizer.new(redacao_user, action).access_granted).to be_truthy
end
end
def check_if_rules_are_synced!
unless yield
fail("Configured allowed actions in the spec are not in sync with the ones configured in the Authorizer class.")
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment