我在models/ability.rb
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new
if user.role? :registered
can :read Post
end
end
当我在rails console上执行此操作时
#this returns a user with a role: "registered" attribute
user = User.first
post = Post.first
ability = Ability.new(user)
### This returns false ###
ability.can?(:read, post)
#=> false
我编写的这个规范测试能力也失败了,而我希望它能够通过。
describe User, :type => :model do
let(:post) {create(:post)}
describe "abilities" do
subject(:ability){Ability.new(user)}
let(:user){nil}
context "when is a registered user" do
## the default value for the role attribute in the user factory is "registered"
let(:user) {create(:user)}
it {is_expected.to be_able_to :read, post}
end
end
end
当我在浏览器上作为注册用户进行身份验证时,我可以访问和阅读/posts
和/posts/:id
中的帖子,我不知道为什么它在rails console和rspec中都失败了。< / p>
答案 0 :(得分:1)
在discussion之后,我们得出结论,问题是
解决方法 - 解决方案是通过在application.rb
require "#{Rails.root/app/models/ability.rb}"