Back to Repositories

Testing ActiveStorage Direct Upload Integration in rails_admin

This test suite validates ActiveStorage field functionality in Rails Admin, focusing on direct upload capabilities and integration with request handling. It ensures proper file attachment, storage, and user interaction within the admin interface.

Test Coverage Overview

The test suite covers direct file upload functionality for ActiveStorage fields in Rails Admin.

  • Tests file attachment and persistence
  • Validates successful update notifications
  • Verifies filename integrity after upload
  • Handles ActiveStorage DirectUploadsController integration

Implementation Analysis

The testing approach utilizes RSpec request specs with JavaScript support for dynamic file uploads.

Implementation leverages FactoryBot for test data generation and incorporates URL blacklisting to prevent SQLite3 locking issues during file processing. The tests follow a behavior-driven development pattern with clear setup and verification steps.

Technical Details

  • RSpec request specs with :js flag
  • ActiveStorage integration
  • FactoryBot for test data
  • Capybara for page interaction
  • URL blacklist configuration for stability
  • Direct upload configuration in RailsAdmin

Best Practices Demonstrated

The test implementation showcases several testing best practices for Rails Admin components.

  • Proper test isolation and cleanup
  • Clear subject definition
  • Explicit expectations and verifications
  • Resource cleanup in after blocks
  • Configuration scoping within test context

railsadminteam/rails_admin

spec/integration/fields/active_storage_spec.rb

            
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'ActiveStorage field', type: :request, active_record: true do
  subject { page }
  let(:field_test) { FactoryBot.create :field_test }
  before do
    # To suppress 'SQLite3::BusyException: database is locked' exception
    @original = page.driver.browser.url_blacklist # rubocop:disable Naming/InclusiveLanguage
    page.driver.browser.url_blacklist = [%r{/rails/active_storage/representations}] # rubocop:disable Naming/InclusiveLanguage
  end
  after { page.driver.browser.url_blacklist = @original } # rubocop:disable Naming/InclusiveLanguage

  describe 'direct upload', js: true do
    before do
      RailsAdmin.config FieldTest do
        edit do
          field(:active_storage_asset) { direct true }
        end
      end
    end

    it 'works' do
      visit edit_path(model_name: 'field_test', id: field_test.id)
      attach_file 'Active storage asset', file_path('test.jpg')
      expect_any_instance_of(ActiveStorage::DirectUploadsController).to receive(:create).and_call_original
      click_button 'Save'
      expect(page).to have_content 'Field test successfully updated'
      field_test.reload
      expect(field_test.active_storage_asset.filename).to eq 'test.jpg'
    end
  end
end