2014-09-04 19 views
0

这里是我最简单的能力类:模拟的能力类

class Ability 
    include CanCan::Ability 

    def initialize(user) 
     if user.has_role? :admin 
      can :manage, :control_panel 
     end 
    end 
end 

我应该如何嘲笑它在一个控制器规范?

这里是我的控制面板控制器:

class Admin::ControlPanelController < ApplicationController 
    authorize_resource class: false 

    rescue_from CanCan::AccessDenied do |exception| 
     redirect_to root_url, danger: "#{exception}" 
    end 

    def statistics 
    end 
end 

这里是我的CONTROL_PANEL控制器规格:

describe '#statistics:' do 
    let(:request){ get :statistics } 

    context 'When guest;' do 
     before do 
      # HOW SHOULD I MOCK HERE? 
     end 

     describe 'response' do 
      subject { response } 

      its(:status){ should eq 302 } 
      its(:content_type){ should eq 'text/html' } 
      it{ should redirect_to root_path } 
     end 

     describe 'flash' do 
      specify { expect(flash[:danger]).to eq "You do not have sufficient priviledges to access the admin area. Try logging in with an account that has admin priviledges." } 
     end 
    end 

我应该如何嘲笑的能力吗?之前,我这样做:

let(:user){ FactoryGirl.create :user } 
expect(controller).to receive(:current_user).and_return user 
expect(user).to receive(:has_role?).with(:admin).and_return false 

但是这是我使用的康康舞,并手动检查用户有一定的作用了。这种行为发生在应用程序控制器中,所以非常容易模拟。我有困难:(

我想嘲弄它在不同环境下嘲讽这个技能类,我感觉有点失落,因为即使我这样做:。

expect(Ability).to receive(:asdasdadskjadawd?).at_least(:once) 

不会引发错误,虽然一个,如果我做拼写“能力”说错了,它的嘲讽类OK提高...

回答

0

我不认为你应该嘲讽Ability类,尤其不要在控制器试验,Ability类更像是配置而不是代码;它在应用程序中不会改变,它也是n控制器不应该关心的实现细节。你应该嘲笑你的Users。看起来你正在使用FactoryGirl;你可以使用FactoryGirl's traits嘲笑各类用户,您有:如果

FactoryGirl.define do 
    factory :user do 
    name 'Bob' 
    email '[email protected] 
    role 'user' 

    trait :admin do 
     role 'admin' 
    end 

    trait :guest do 
     role 'guest' 
    end 
    end 
end 

然后可以使用FactoryGirl.create :user如果你需要一个普通用户,并FactoryGirl.create :user, :admin测试需要一个管理员。