Back to Repositories

Testing CanCanCan Authorization Adapter Integration in Rails Admin

This test suite validates the CanCanCan authorization adapter integration with Rails Admin, focusing on initialization and configuration capabilities. The tests ensure proper ability class handling and block DSL support for authorization setup.

Test Coverage Overview

The test coverage focuses on the initialization behavior of the CanCanCan authorization adapter in Rails Admin. Key areas tested include:

  • Ability class assignment through direct initialization
  • Block DSL configuration support
  • Integration with controller and user contexts
  • Basic authorization rule validation

Implementation Analysis

The testing approach employs RSpec’s describe/it blocks with let statements for dependency setup. The implementation uses doubles for user and controller objects, demonstrating proper isolation of the authorization adapter. The tests leverage RSpec’s expectation syntax to verify correct ability class assignment and DSL configuration.

Technical Details

Testing tools and configuration:

  • RSpec as the testing framework
  • CanCanCan integration for authorization
  • Mock objects using RSpec doubles
  • Custom MyAbility class implementing CanCan::Ability
  • Rails Admin extension testing structure

Best Practices Demonstrated

The test suite exemplifies several testing best practices:

  • Proper test isolation using doubles
  • Clear context separation with describe blocks
  • Focused test cases with single assertions
  • Clean setup using let statements
  • Meaningful test descriptions

railsadminteam/rails_admin

spec/rails_admin/extentions/cancancan/authorization_adapter_spec.rb

            
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe RailsAdmin::Extensions::CanCanCan::AuthorizationAdapter do
  let(:user) { double }
  let(:controller) { double(_current_user: user, current_ability: MyAbility.new(user)) }

  class MyAbility
    include CanCan::Ability
    def initialize(_user)
      can :access, :rails_admin
      can :manage, :all
    end
  end

  describe '#initialize' do
    it 'accepts the ability class as an argument' do
      expect(described_class.new(controller, MyAbility).ability_class).to eq MyAbility
    end

    it 'supports block DSL' do
      adapter = described_class.new(controller) do
        ability_class MyAbility
      end
      expect(adapter.ability_class).to eq MyAbility
    end
  end
end