我正在尝试使用具有用户的用户的系统。到目前为止没有问题。我创建了两个角色:员工和:老板,老板可以有很多员工,员工必须有一个老板。
我在rails应用程序上使用devise,cancan,mongoid,问题是设置ability.rb文件,我认为没关系,但是当我尝试在rspec上测试它时,它会失败。
ability.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
和spec文件:
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
默认情况下,工厂将用户创建为boss。我运行测试并获得:
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
仍有同样的问题,但现在更清晰
答案 0 :(得分:0)
我终于解决了这个问题,我为其他像我这样的新人提出了解决方案:
if user.role? == :boss
can :crud, User, User.where(:user_id => user.id)
end
这必须改变:
if user.role? == :boss
can :crud, User, :user_id => user.id
end