2014-01-21 49 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。你在使用哪个驱动程序?