Back to Repositories

Testing ActiveRecordEnum Field Type Implementation in rails_admin

This test suite validates the ActiveRecordEnum field type implementation in RailsAdmin, focusing on enum field handling and value formatting. It ensures proper integration with different ActiveRecord versions and enum configurations.

Test Coverage Overview

The test suite provides comprehensive coverage of ActiveRecordEnum field type functionality in RailsAdmin.

  • Validates generic field type behavior for string enum fields
  • Tests enum value formatting and display
  • Handles different ActiveRecord version compatibilities
  • Verifies proper enum configuration parsing

Implementation Analysis

The testing approach employs RSpec’s shared examples pattern for consistent field type validation. It specifically focuses on the pretty_value method implementation, using a FormatAsEnum test class to simulate real-world enum usage.

  • Implements version-specific enum syntax handling
  • Uses context blocks for specific test scenarios
  • Employs before blocks for test setup

Technical Details

  • RSpec testing framework
  • ActiveRecord integration testing
  • Shared example patterns
  • Dynamic field configuration
  • Version-specific code paths
  • Custom test class definition

Best Practices Demonstrated

The test suite exemplifies several testing best practices in Ruby and RSpec.

  • Isolated test contexts
  • Clear test case organization
  • Version-aware implementation
  • Proper setup and teardown
  • Explicit expectations
  • DRY testing patterns

railsadminteam/rails_admin

spec/rails_admin/config/fields/types/active_record_enum_spec.rb

            
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe RailsAdmin::Config::Fields::Types::ActiveRecordEnum, active_record: true do
  it_behaves_like 'a generic field type', :string_enum_field

  describe '#pretty_value' do
    context 'when column name is format' do
      before do
        class FormatAsEnum < FieldTest
          if ActiveRecord.gem_version >= Gem::Version.new('7.0')
            enum :format, {Text: 'txt', Markdown: 'md'}
          else
            enum format: {Text: 'txt', Markdown: 'md'}
          end
        end
      end
      let(:field) do
        RailsAdmin.config(FormatAsEnum).fields.detect do |f|
          f.name == :format
        end.with(object: FormatAsEnum.new(format: 'md'))
      end

      it 'does not break' do
        expect(field.pretty_value).to eq 'Markdown'
      end
    end
  end
end