使用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
角色的resource attributes权限设置了。 (请注意,我正在使用实现此类功能的CanCan 2.0版本。)
以下是对属性执行授权检查的表单视图:
# 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'