2014-09-04 61 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測試需要一個管理員。