Ruby on rails cancan rspec测试时的意外行为
我正在根据本指南测试cancan能力: 这是我的能力档案: 更新:我已经发布了所有能力文件Ruby on rails cancan rspec测试时的意外行为,ruby-on-rails,ruby,rspec,cancan,Ruby On Rails,Ruby,Rspec,Cancan,我正在根据本指南测试cancan能力: 这是我的能力档案: 更新:我已经发布了所有能力文件 #models/ability.rb class Ability include CanCan::Ability def initialize(user) user ||= User.new(role:Role.find_by(name:'guest')) # in case of guest if user.has_role? :admin can :manage, :all end if u
#models/ability.rb
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new(role:Role.find_by(name:'guest')) # in case of guest
if user.has_role? :admin
can :manage, :all
end
if user.has_role? :author
can :read, :all
can :create, Msg
can :create, Post
can :destroy, Msg, user_id:user.id
can :destroy, Post, user_id:user.id
can :update, Post, user_id:user.id
can :update, Msg, user_id:user.id
can :destroy, Msg, post: { user_id:user.id }
end
if user.has_role? :moderator
can :read, :all
can :create, Msg
can :destroy, Msg
can :update, Msg , user_id:user.id
end
if user.has_role? :guest
can :read, Msg
can :read, Post
end
if user.has_role? :user
can :read, :all
can :create, Msg
can :destroy, Msg , user_id:user.id
can :update, Msg , user_id:user.id
end
end
这是我的规格测试:
require "cancan/matchers"
require 'spec_helper'
describe "when is moderator" do
before do
@u=FactoryGirl.create(:moderator)
@p=FactoryGirl.create(:post,user_id: 1245)#To be sure @p don't belongs to @u
@a=Ability.new(@u)
end
it{ @a.should be_able_to(:update, Post) } #Ok, it must be pass
it{ @a.should be_able_to(:update, FactoryGirl.create(:post,:user_id => @u.id)) } #Ok, it must be pass
it{ @a.should be_able_to(:update,@p) } #passed, ***but should fail***
end
我不知道该怎么解决,在我看来,这种行为是独立的这并不能解决你的问题,但你应该编写测试,这样,当你的应用程序正常运行时,它们都会通过。因此,在这种情况下,你应该使用
should\u not
而不是should
的方法来进行第三次断言。如果我的能力是正确的,那么第三次断言肯定是失败的,我想。post allability.rb
我已经发布了所有的能力。你检查过@p.user\u id
实际上是1245
(即,您的工厂按预期工作)?