0
我想要做一個讓用戶擁有用戶的系統。到目前爲止沒有問題。我創建了兩個角色:員工和老闆,老闆可以有很多員工,員工必須有一個老闆。有很多用戶的Rails cancan用戶
我用的設計,康康舞,mongoid在Rails應用程序,問題設置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
工廠創建用戶作爲老闆默認。我運行測試並獲得:
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: "[email protected]", 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: 我已經refactoriced在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
仍然有同樣的問題,但現在更爲清晰可辨