2012-02-16 3 views
3

CanCan 어빌리티를 처음으로 테스트 중이며 난감합니다. 내가 뭔가를 놓치고있어 ... 비록 내가 false/true can의 내부를 반환하더라도 : invite_to block 나는 여전히 스펙을 얻지 못하고있다. CanCan matchers를 사용하여 실종 되었습니까? 또는 스텁? 또는 CanCan에서 능력을 결정할 수 있습니까?RSpec으로 CanCan 어빌리티를 올바르게 테스트하는 방법

내가 누락 된 부분이 있습니까?

class Ability 
    include CanCan::Ability 

    def initialize(user) 
    user ||= User.new 

    can :invite_to, Network do |network| 
     network.allows_invitations? && (user.admin? || user.can_send_invitations_for?(network)) 
    end 
    end 
end 

ability_spec.rb

require 'cancan' 
require 'cancan/matchers' 
require_relative '../../app/models/ability.rb' 

class Network; end; 

describe Ability do 
    let(:ability) { Ability.new(@user) } 

    describe "#invite_to, Network" do 
    context "when network level invitations are enabled" do 
     let(:network) { stub(allows_invitations?: true) } 

     it "allows an admin" do 
     @user = stub(admin?: true) 
     ability.should be_able_to(:invite_to, network) 
     end 

     it "allows a member if the member's invitation privileges are enabled" do 
     @user = stub(admin?: false, can_send_invitations_for?: true) 
     ability.should be_able_to(:invite_to, network) 
     end 

     it "denies a member if the member's invitation privileges are disabled" do 
     @user = stub(admin?: false, can_send_invitations_for?: false) 
     ability.should_not be_able_to(:invite_to, network) 
     end 
    end 
    end 
end 

실패

1) Ability#invite_to, Network when network level invitations are enabled allows an admin 
    Failure/Error: ability.should be_able_to(:invite_to, network) 
     expected to be able to :invite_to #<RSpec::Mocks::Mock:0x3fe3ed90444c @name=nil> 
    # ./spec/models/ability_spec.rb:16:in `block (4 levels) in <top (required)>' 

    2) Ability#invite_to, Network when network level invitations are enabled allows a member if the member's invitation privileges are enabled 
    Failure/Error: ability.should be_able_to(:invite_to, network) 
     expected to be able to :invite_to #<RSpec::Mocks::Mock:0x3fe3edc27408 @name=nil> 
    # ./spec/models/ability_spec.rb:21:in `block (4 levels) in <top (required)>' 

답변

4
let(:network) do 
    n = Network.new 
    n.stub!(:allows_invitations? => true) 
    n 
    end 
,745 ability.rb

작성한대로 코드를 실행하면 Can 블록 안의 코드에 절대로 도달하지 않습니다. 스텁에 대한 호출은 RSpec :: Mocks :: Mock 클래스의 객체를 반환합니다. 규칙을 적용하려면 CanCan 용 Network 클래스 여야합니다.

+0

탁월한 캐치. 방금 인스턴스 대신 클래스가 주어질 때 블록을 건너 뛰는 것에 대한 설명서의 해당 부분을 읽었습니다. 그래도 클릭하지 않았습니다. 감사. –

관련 문제