[英]Cancancan ability debugging fails in rails console and Rspec
I have this in models/ability.rb
我在
models/ability.rb
有这个
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new
if user.role? :registered
can :read Post
end
end
When I do this on rails console当我在 rails 控制台上执行此操作时
#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
This spec I have written to test the ability also fails while i expect it to pass.我为测试能力而编写的这个规范也失败了,而我希望它通过。
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
I can access and read posts in both /posts
and /posts/:id
when I am authenticated as a registered user on the browser, I have no idea why it is failing in both rails console and rspec.当我在浏览器上作为注册用户进行身份验证时,我可以访问和阅读
/posts
和/posts/:id
,但我不知道为什么它在 rails 控制台和 rspec 中都失败了。
Following our discussion , we concluded that the problem is either经过我们的讨论,我们得出结论,问题要么是
The workaround-solution is to manually load the Ability file by appending the following at the end of the application.rb
解决方法是通过在
application.rb
的末尾附加以下内容来手动加载 Ability 文件
require "#{Rails.root}/app/models/ability.rb"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.