对于ActiveModel,Rails未定义方法none

时间:2015-12-29 16:07:25

标签: ruby-on-rails ruby rspec

我遇到一个未定义的方法错误,在Pundit Policy中测试以下代码。 我在教自己RoR所以这可能非常明显。但是我不知道为什么会出现这个错误。范围似乎是我想测试的Project类,似乎是一个ActiveRecord类。查看API文档应该包含方法none,但根据测试运行不包含。

class ProjectPolicy < ApplicationPolicy
    class Scope < Scope
        def initialize(user, scope)
            @user = user;
            @scope = scope;
        end 

        def resolve
            return scope.none if user.nil?
            return scope.all if user.admin?

            scope.joins(:roles).where(roles: {user_id: user})
        end
    end
end

这是我运行的rspec测试。

require 'rails_helper'

describe ProjectPolicy do

    let(:user) { User.new }

    subject { described_class }

    context "policy_scope" do
        subject { Pundit.policy_scope(user, Project) }

        let!(:project) { FactoryGirl.create :project }
        let!(:user) { FactoryGirl.create :user }

        it "is empty for anonymous users" do
            expect(Pundit.policy_scope(nil, project)).to be_empty
        end
    end
end

这是运行测试时的堆栈跟踪。

1) ProjectPolicy policy_scope is empty for anonymous users
   Failure/Error: return scope.none if user.nil?

   NoMethodError:
     undefined method `none' for #<Project:0x007fb0f45c0010>
   # /Users/mquellhorst/.rbenv/versions/2.2.4/lib/ruby/gems/2.2.0/gems/activemodel-4.2.4/lib/active_model/attribute_methods.rb:433:in `method_missing'
   # ./app/policies/project_policy.rb:6:in `resolve'
   # /Users/mquellhorst/.rbenv/versions/2.2.4/lib/ruby/gems/2.2.0/gems/pundit-1.0.1/lib/pundit.rb:49:in `policy_scope'
   # ./spec/policies/project_policy_spec.rb:51:in `block (3 levels) in <top (required)>'
   # /Users/mquellhorst/.rbenv/versions/2.2.4/lib/ruby/gems/2.2.0/gems/rspec-core-3.4.1/lib/rspec/core/example.rb:236:in `instance_exec'

1 个答案:

答案 0 :(得分:1)

您使用Pundit.policy_scope(nil, project)实例(您在Project中创建的那个)调用let(:project) ActiveRecord#none上定义了Project,这就是它在subject块中的作用。比较:

Project.none     #=> #<ActiveRecord:Relation []>
Project.new.none #=> Your current error