我正在尝试做一个有用户有用户的系统。到目前为止没有问题。我创建了两个角色,:employee 和:boss,一个老板可以有多个员工,一个员工必须有一个老板。
我在rails应用程序上使用devise、cancan、mongoid,问题是设置ability.rb文件,我认为没问题,但是当我尝试在rspec上测试它时,它失败了。
能力.rb
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user (not log in)
alias_action :read, :create, :update, :destroy, :to => :crud
if user.role? == :boss
can :crud, User do |people|
user.users.include?( people )
end
end
end
end
和规范文件:
require 'cancan'
require 'cancan/matchers'
require_relative '../../app/models/ability.rb'
require 'spec_helper'
describe Ability do
let(:user) { FactoryGirl.create(:user) }
describe "role user system" do
context "when there are a boss" do
before(:each)do
@user = user
@ability = Ability.new(@user)
@emplo = FactoryGirl.create(:user, :role => :employee, :user => @user)
end
it "allows to crud employees" do
@ability.should be_able_to(:crud, @emplo)
end
it "denies a non boss user to manage employees" do
ability1 = Ability.new(FactoryGirl.create(:user, :role => :employee))
ability1.should_not be_able_to(:manage, @emplo)
end
end
end
end
工厂默认创建用户为老板。我运行测试并获得:
Ability
role user system
when there are a boss
allows to crud employees (FAILED - 1)
denies a non boss user to manage employees
Failures:
1) Ability role user system when there are a boss allows to crud employees
Failure/Error: @ability.should be_able_to(:crud, @emplo)
expected to be able to :crud #<User _id: 518b5a860009d6307f000002, _type: nil,
email: "user-2@example.org", encrypted_password: "$2a$04$OJeSUDPFf223r79jJP6odeBcuRoBJa1y0u3omOnAsE7SUyPwtgdmW",
reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil,
sign_in_count: 0, current_sign_in_at: nil, last_sign_in_at: nil, current_sign_in_ip: nil,
last_sign_in_ip: nil, confirmation_token: nil, confirmed_at: 2013-05-09 08:12:54 UTC,
confirmation_sent_at: nil, unconfirmed_email: nil, address: "C\\ Romeo love Julieta street, 9, 5º A",
name: "fooname", surname: "foosurname", phone: "+34957957957", role: :employee, user_id: "518b5a860009d6307f000001">
我做错了什么,我在互联网上搜索,但我没有找到答案。谢谢。
PD:我已经重构了ability.rb 文件
if user.role? == :boss
can :crud, User do |people|
user.users.include?( people )
end
end
为了
if user.role? == :boss
can :crud, User, User.where(:user_id => user.id)
end
仍然有同样的问题,但现在更清晰了