我正在使用cancan創業板,但都遇到了一些問題。我寫了一些簡單的測試,失敗的用戶沒有分配給他們的角色。可以看出,在Ability類中,我嘗試說只有當用戶具有以下角色時,用戶才能管理其他用戶:admin。正如評論所述,該塊永遠不會被調用。CanCan似乎無視塊
在cancan gem中,當你將一個塊傳遞給can時?方法,它將該規則添加到規則中,然後在調用can時調用該規則?方法,除非傳入的對象的類是Class。所以當我執行下面的測試時,它失敗了,因爲我傳遞了User和User.class == Class。
it { should_not be_able_to(:create, User) }
or
it "cannot create a User" do
expect(ability.cannot? :create, User).to be_true
end
考慮到這一點,如果我寫一個測試,在一個特定的用戶測試的測試通過:
it { should_not be_able_to(:edit, FactoryGirl.create(:user)) } # passes, but...
但是,讓當你上市,或創建沒有意義:
it { should_not be_able_to(:create, FactoryGirl.create(:user)) } # yuck
我想你可以使用
it { should_not be_able_to(:create, User.new) } # but that is still full of suck
參考編碼:
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new
can :manage, User do |u|
# this block never gets called
user.has_role? :admin
end
end
end
describe "user without roles" do
subject { ability }
let(:ability) { Ability.new create(:user) }
it { should_not be_able_to(:manage, User) } # passes
it { should_not be_able_to(:index, User) } # all the rest fail
it { should_not be_able_to(:new, User) }
it { should_not be_able_to(:edit, User) }
it { should_not be_able_to(:create, User) }
it { should_not be_able_to(:update, User) }
end
# CANCAN CODE
# https://github.com/ryanb/cancan/blob/c88cb8f4593148f99e15627d23fbf67116dd8be2/lib/cancan/can_definition.rb#L32
def matches_conditions?(action, subject, extra_args)
if @match_all
call_block_with_all(action, subject, extra_args)
## The condition in question, this is where I should go to
## subject -> User
## User.class -> Class
elsif @block && !subject_class?(subject)
@block.call(subject, *extra_args)
elsif @conditions.kind_of?(Hash) && subject.kind_of?(Hash)
nested_subject_matches_conditions?(subject)
elsif @conditions.kind_of?(Hash) && !subject_class?(subject)
matches_conditions_hash?(subject)
else
@base_behavior
end
end
# User class returns true
def subject_class?(subject)
(subject.kind_of?(Hash) ? subject.values.first : subject).class == Class
end
由於cancan非常受歡迎,我把錢放在事實上我做錯了事實。任何幫助將不勝感激。