我有一个没有模型的控制器,并且我有三个由整数定义的角色。 [1代表 admin ,2代表 Team Leader ,3代表 Team Member 。我想做的是,我想在RSpec
中测试通过cancancan
授权可以正确访问我的控制器动作。到目前为止,我已经为 Team Member 应用了授权,并且能够在前端正确渲染视图。但是如果进行测试,我会报错。
#My TeamMember Controller File
class TeamMemberController < ApplicationController
authorize_resource :class => TeamMemberController
def index
@user = User.new
user = User.find(session[:current_user_id])
if user.status == 1
total_leave = 21
elsif user.status == 2
total_leave = 17
end
available_leave = user.leave_balance
session[:total_leave] = total_leave
session[:available_leave] = available_leave
@leaves = Leave.where(user_id: session[:current_user_id])
end
def logOut
reset_session
redirect_to(:controller => 'user', :action => 'index')
end
end
Ability.rb
#My Ability.rb file
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new
if user.present?
if user.role == 3
can [:index, :logOut], [:TeamMemberController]
end
end
end
end
我的RSpec文件
describe User do
subject(:ability){ Ability.new(user) }
let(:user){ FactoryBot.build(:user, role: 3) }
context "when is a Team Member" do
let(:role) {FactoryBot.build(:user)}
it "Should be able to Index#TeamMember" do
should be_able_to :index, TeamMemberController
end
end
end
用于创建用户的工厂文件
factory :user do
id {45}
team_lead_id {2}
name {'Test Name'}
email {'Test Email'}
password {'Test Password'}
joining_date {'2018-04-04'.to_date}
status {2}
role {3}
leave_balance {17}
encrypted_password {"Test"}
confirmation_token {"Test"}
remember_token {"Test"}
end
我得到的错误是
User when is a Team Member Should be able to Index#TeamMember
Failure/Error: should be_able_to :index, TeamMemberController
expected to be able to index TeamMemberController
那么,如何检查在cancancan
中使用RSpec
的控制器操作?