Search code examples
ruby-on-railsrubypundit

Method with ? in name throws no method errors in pundit policy


I am using Pundit but cannot find how to set a method in my policy that ends with a question mark.

I have a method in my sessions controller called is_logged_in? and in the sessions policy I have the same method with the correct security logic associated with it. However, when I try to access the method, I get these errors because the policy cannot find the method:

Minitest::UnexpectedError: NoMethodError: undefined method is_logged_in?? for #<SessionPolicy:0x007f9530200bd0>

Of course rails methods cannot have multiple question marks so how do I tell my policy that this is the method?

I am using

  • Ruby 2.3.3
  • Rails 4.2.7.1
  • Pundit 2.1.0

Policy:

class SessionPolicy < ApplicationPolicy
  def create?
    true
  end

  def new?
    true
  end

  def destroy?
    true
  end

  def is_logged_in?
    true
  end
end

Testing it with (Minitest):

 test "is_logged_in? should return false when NOT logged in" do
    sign_out get_user
    get :is_logged_in?
    assert_response :ok
    response = response_to_json
    assert !response[:logged_in]
    assert !response[:is_business]
  end

API:

def is_logged_in?
    payload = {
      logged_in: !current_user.nil?,
      is_business: current_user.try(:is_business?)
    }
    render json: payload, status: :ok
  end

Other than this unit test and before using Pundit for the Authorization, I was able to hit this end-point from my front end application.


Solution

  • The policy method is determined by appending a ? to the end of your controller action name. Your controller action name should not end in a ? as this wouldn't constitute a proper URI path.

    Although your post did not show any controller code, the test in question should say get :is_logged_in.