3

How do you test a controller action (eg. show) for an authorized user when the app uses Pundit for authorization.

Info:

class PlansController < ApplicationController

  before_action :authenticate_user!


  def show
    @plan = Plan.find(params[:id])
    authorize @plan
  end
  .
  .
end

class PlanPolicy < ApplicationPolicy

  def show?
    record.users.include? user
     end

    end

require 'test_helper'

class PlansControllerTest < ActionController::TestCase

test 'When user is authorized should get show' do
    @plan = @planone
    sign_in @userdom
    # what do I put here?
    get :show, id: @plan
    assert_response :success
    assert_select "title", "Show plan | Plennel"
  end
end

I already test the plan_policy in plan_policy_test.rb. Some options I have tried are:

Setting authorize to true in the controller test.

Skipping authorize in the controller test.

Solutions I have found are either using RSpec (while I use Minitest with fixtures) or Mocha or go into detail with regard to testing Pundit policies but don't explain testing controller actions that require an authorized user.

I am looking for a simple way to skip (or fake) authorization in tests without the use of gems or other test suites than Minitest. I have been trying to get my head around this for for two days now so help would be greatly appreciated!

btw: I still have a lot to learn with regard to Rails development so apologies if I'm asking the wrong questions or if I'm giving the wrong info.

domtiedom
  • 61
  • 5
  • Hey buddy, I think I asked a similar question and answered it myself here using Mini Test: https://stackoverflow.com/questions/40690056/rails-pundit-mini-test-assert-response-punditnotauthorizederror/40690092#40690092 – Zhang May 20 '19 at 05:02

1 Answers1

1

authorize calls show? method in PlanPolicy beneath the hood. You just need to stub that to return true.

To do it in plain Ruby, you'd put something like this at the start of your spec.

class PlanPolicy
  def show? ; true ; end
end

I'm not familiar with Minitest, but it should support stubbing too.

fylooi
  • 3,840
  • 14
  • 24
  • For some reason I get an unknown method error when I try the above. Not being able to find a solution I have installed the Mocha gem and use `policy = stub(create?: true); PlanPolicy.stubs(:new).returns(policy)` Needing a gem just to be able to stub Pundit policies is not my first pick but for now it'll have to do. – domtiedom Feb 09 '16 at 22:15