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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With