Как протестировать разные роли пользователя с капибарой
Как лучше всего протестировать различные роли авторизации, основанные на способностях, с помощью CanCan и Capybara?
Я мог бы написать feature
для каждой роли, но, как вы можете видеть в Ability
класс, :editor
а также :administrator
роли имеют много общего, и это может привести к загромождению и повторению кода. Я уже проверил мой Ability
Класс с юнит-тестами, как указано в документации, но тестирование с Capybara кажется другим. Я мог бы соединить тест редактора и администратора для большинства частей с некоторыми условиями, чтобы сделать его простым и коротким, но соединение плохое.
Вот мой Ability
учебный класс:
# app/models/ability.rb
class Ability
include CanCan::Ability
def initialize(account)
account || Account.new
alias_action :create, :read, :update, :destroy, to: :crud
if account.role? :client
can :crud, :dashboards
cannot :crud, :accounts
can :update, :accounts, id: account.id
cannot :update, :accounts, [:role, :username], id: account.id
cannot :crud, :sites
can :read, :sites, account_id: account.id
can :update, :sites, [:name, :description, :locales,
:google_verification_code, :social_links,
:display_social_icons], account_id: account.id
can :crud, :pages, site: { account_id: account.id }
cannot :crud, [:themes]
elsif account.role? :editor
can :crud, :accounts, role: ['editor', 'client']
can :crud, :sites
can :crud, :pages
elsif account.role? :administrator
can :crud, :all
end
end
end
Как вы можете видеть выше, для атрибутов ресурса установлены :client
Роль, которая проверяется при взгляде. (Обратите внимание, что я использую версию 2.0 CanCan, которая реализует такую функцию.)
Вот представление формы, которое выполняет проверку полномочий для атрибутов:
# app/views/backoffice/sites/_form.html.haml
= simple_form_for [:backoffice, @site] do |f|
.row
.col-lg-12
.panel.panel-default
.panel-heading
%h4 Information Panel
.panel-body
= f.association :account if can? :update, @site, :account_id
= f.input :primary_domain_name if can? :update, @site, :primary_domain_name
= f.input :name if can? :update, @site, :name
= f.input :description if can? :update, @site, :description
= f.input :google_verification_code if can? :update, @site, :google_verification_code
= f.input :activated_at, as: :string if can? :update, @site, :activated_at
= f.input :expired_at, as: :string if can? :update, @site, :expired_at
= f.association :theme if can? :update, @site, :theme_id
= f.submit @site.new_record? ? t('actions.create') : t('actions.update'), class: 'btn'