2013-03-02 91 views
0

我正在使用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非常受歡迎,我把錢放在事實上我做錯了事實。任何幫助將不勝感激。

回答

0

它看起來像下面的代碼是我應該有能力類:

can :manage, User if user.has_role? :admin 
0

不要使用| U |在您的區塊中:

can :manage, User do |u| 
    u.has_role? :admin 
end 

嘗試使用https://gist.github.com/fotinakis/3a532a0929f64b4b5352進行測試。他們看起來如下:

context "user without roles" do 
    it "can view everything" do 
    expect(@guest).to have_ability(:read, for: "all") 
    end 

    it "cannot edit or delete anything" do 
    expect(@guest).to_not have_ability(:manage, for: "all") 
    end 
end