2015-12-27 27 views
1

在我的rails應用程序中,我有兩個用戶角色:'student'和'admin'。他們對不同頁面擁有不同的訪問權限,例如,'admin'可以訪問列表用戶頁面(索引),但'學生'不能訪問。這是使用cancancan控制的。如何使用默認測試框架(minitest)在控制器測試中測試cancancan功能

現在我寫測試的控制器和,因爲我有兩個不同的角色,(據我所知)我需要一個行爲的兩個獨立的測試,例如:

test "should get index for admin" do 
    sign_in(users(:admin)) 
    get "index" 
    assert_response :success 
end 

test "should not get index for student" do 
    sign_in(users(:student)) 
    get "index" 
    assert_response :unauthorized 
end 

其中sign_in(*)是方法用於處理用戶登錄(會話等)

由於我正在考慮添加更多角色(例如'manager','agent'),因此每次添加角色時都需要爲所有控制器方法添加新測試。這是乏味的,而不是「幹」,所以我試圖找到一個更優雅的方式來處理這個問題。這是我的第一個想法:

在我test_helper.rb中,我說:

def assert_admin_only(&block) 
    sign_in(users(:admin)) 
    instance_exec(&block) 
    assert_response :success 
    sign_out 

    sign_in(users(:student)) 
    instance_exec(&block) 
    assert_response :unauthorized 
    sign_out 

    sign_in(users(:agent)) 
    instance_exec(&block) 
    assert_response :unauthorized 
    sign_out 
end 

然後在我的測試:

test "should get index for admin only" do 
    assert_admin_only do 
     get "index" 
    end 
end 

所以,每次我添加了一個新的角色,我只必須在test_helper.rb方法中添加幾行以測試這些功能。

但是,它並不像我想的那樣工作,因爲「功能測試允許您測試每個測試方法的單個控制器操作。」根據Rails API DOC,而在我的代碼中,我發射了兩個動作甚至更多。出於某種原因,我無法弄清楚,似乎sign_insign_out實際上並沒有改變current_user(儘管它們在真正的請求中完美地工作),這基本上使我的嘗試失敗。

總而言之,我想重新使用我的測試來處理不同的用戶角色,這樣我就不必在每次添加新角色時都浪費時間複製和粘貼現有代碼。如果你們能提供一些出色的想法,我將非常感激。

回答

0

例如:

require 'test_helper' 

class ArticlesControllerTest < ActionController::TestCase 
    include Devise::TestHelpers 

    setup do 
    @article = articles(:one) 
    @admin = users(:admin) 
    @expert = users(:expert) 
    @user = users(:emelya) 
    @student = users(:student) 
    end 

    test "should get index if admin" do 
    sign_in @admin 
    ability = Ability.new(@admin) 
    assert ability.can? :index, Article 

    get :index 
    assert_response :success 
    assert_not_nil assigns(:articles) 
    end 


    test "should not get index for other users" do 
    [@expert, @user, @student] do |user| 
     sign_in user 
     ability = Ability.new(user) 
     assert ability.cannot? :index, Article 

     assert_raise CanCan::AccessDenied do 
     get :index 
     end 

     sign_out user 
    end 
    end 

end