Michiel
Michiel

Reputation: 1051

Rails undefined method none for ActiveModel

I run into an undefined method error running testing the following code in a Pundit Policy. I'm teaching myself RoR so this could be just very obvious. However I have no idea why this error is occurring. The scope seems to be the Project class I want to test and seem to be an ActiveRecord class. Looking at the API documentation is should contain the method none but according to the test run is does not.

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

This is the rspec test I run.

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

This is the stack trace when running the test.

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'

Upvotes: 0

Views: 670

Answers (1)

Kristj&#225;n
Kristj&#225;n

Reputation: 18803

You're calling Pundit.policy_scope(nil, project) with an instance of Project (the one you created in let(:project)). ActiveRecord#none is defined on the class Project, which is why it works in the subject block. Compare:

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

Upvotes: 1

Related Questions