2014-01-21 53 views
0

我有一個與Devise和CanCan的Rails 3.2應用程序。用戶能力由角色定義。數據庫中有五個角色,id值爲1-5,通過成員資格擁有用戶has_one角色。因此,例如,Membership.create(user_id: 2, role_id: 4)會導致User.find(2).role == Role.find(4) # => true水豚,CanCan,測試與開發

我的能力,文件看起來像

if user.has_role? :admin 
    can :manage, Model 
    can :manage, AnotherModel 
    # etc. 
elsif user.has_role? :basic 
    can :read, Model 
    can :read, AnotherModel 
elsif user.has_role? (etc. for other roles) 
    (etc.) 
else 
    cannot :manage, :all 

我想踢出來誰是試圖訪問他們沒有授權的網頁的用戶。我的應用程序控制器包括:發展中的點擊左右時

rescue_from CanCan::AccessDenied do |exception| 
    reset_session 
    redirect_to new_user_session_path 
end 

這種現象正常工作 - 通過導軌控制檯創建了一個基本的用戶試圖做的事情管理員時被踢出,並在控制檯中創建的沒有角色的用戶( ,然後User.last.membership.destroy,以便User.last.role # => nil)無法登錄儀表板 - 而是立即將用戶重定向到登錄頁面(沒有角色的用戶無法管理任何內容)。

試圖測試此相同的行爲時,專門爲沒有任何角色的用戶碰到問題:

# spec/support/login_helpers.rb 
def login_via_sign_in_page(user) 
    visit new_user_session_path 
    fill_in :user_email, with: user.email 
    fill_in :user_password, with: user.password 
    click_button 'Sign in' 
end 

# spec/features/dashboard_spec.rb 
describe "as a user with no role" do 
    let(:user) { FactoryGirl.create(:user) } 

    before { login_via_sign_in_page(user) } 

    it "should redirect to the sign_in page" do 
    current_path.should == new_user_session_path 
    end 
end 

上述測試失敗,使用RSpec表明該用戶成功到達儀表盤頁面,而不是被重定向到登錄頁面。但是,下面的規格通過:

# spec/features/dashboard_spec.rb 
describe "as a guest browser (no login whatsoever)" do 
    it "should redirect to the sign_in page" do 
    visit dashboard_index_path 
    current_path.should == new_user_session_path 
    end 
end 

describe "as an admin user" do 
    let(:user) { FactoryGirl.create(:admin_user) } 

    before { login_via_sign_in_page(admin_user) } 

    it "should go to the dashboard" do 
    visit dashboard_index_path 
    current_path.should == dashboard_index_path 
    end 
end 

...以及東西基本一樣的用戶試圖管理行爲

我已閱讀this post,這似乎是處理時被重定向到sign_in頁一個類似的問題,但這些建議並沒有幫助。

最後,當使用debuggersave_and_open_page時,我得到了令人困惑的結果。前者會給我user # => <A legit User object>user.role # => nil。但是,save_and_open_page顯示我在儀表板頁面上登錄。

回答

0

您是否嘗試過使用包括Warden::Test::Helpers以及測試用水豚設計所需的其餘配置?看看這裏How To: Test with Capybara。你在使用哪個驅動程序?