在rails控制台和Rspec中,Cancancan能力调试失败

时间:2016-01-13 12:53:37

标签: ruby-on-rails rspec cancan cancancan

我在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>

1 个答案:

答案 0 :(得分:1)

discussion之后,我们得出结论,问题是

  1. Rails没有加载Ability类,或
  2. 代码某处以某种方式覆盖了Ability类。
  3. 解决方法 - 解决方案是通过在application.rb

    末尾添加以下内容来手动加载Ability文件
    require "#{Rails.root/app/models/ability.rb}"