从评论中扩展。
基于https://github.com/ryanb/cancan/wiki/Testing-Abilities我执行以下测试。
在我的管理员规范中。
require 'spec_helper'
require 'cancan/matchers'
describe Administrator do
describe "abilities" do
subject { ability }
let(:ability) { Ability.new(admin) }
let(:account) { FactoryGirl.create :account, isp: admin.isp }
context "is a helpdesk admin" do
let(:admin) { FactoryGirl.create :helpdesk_admin }
let(:mail_user) {FactoryGirl.create :mail_user, account: account}
let(:web_user) {FactoryGirl.create :web_user, account: account }
let(:radius_user) { FactoryGirl.create :radius_user, account: account}
it { should be_able_to(:change_password,mail_user)}
it { should be_able_to(:change_password,radius_user)}
it { should be_able_to(:change_password,web_user)}
it { should_not be_able_to(:manage, Account.new) }
end
context "is a realm admin" do
let(:admin) { FactoryGirl.create :realm_admin }
it{ should be_able_to(:manage, MailDomain.new)}
it{ should be_able_to(:manage, RadiusDomain.new)}
it{ should be_able_to(:manage, WebDomain.new)}
it{ should be_able_to(:manage, Administrator.new)}
end
end
这让我可以测试每个角色分配的能力
然后在我的功能中/我为每个控制器做这样的事情,以确保我不会忘记授权。
context "regular admin" do
let(:admin) {FactoryGirl.create(:admin)}
before(:each) do
visit login_path
fill_in "email" , with: admin.email
fill_in "password", with: admin.password
click_button "Sign in"
end
it "shoudln't allow them to add new admins" do
visit new_administrator_path
page.should have_content "You are not authorized to access this page."
end
end