Back to Repositories

Validating File Size Constraints in CarrierWave Uploader Implementation

This test suite validates file size constraints in CarrierWave’s upload functionality. It ensures proper handling of file size validation during file caching operations, with comprehensive checks for size range enforcement and appropriate error handling.

Test Coverage Overview

The test suite comprehensively covers file size validation in CarrierWave’s caching process. Key areas include:

  • Unspecified size range handling
  • Below minimum size validation
  • Above maximum size validation
  • Valid size range verification

Implementation Analysis

The testing approach utilizes RSpec’s context-based structure to systematically verify size validation scenarios. It employs let blocks for setup, stubbed methods for controlled testing, and expectation matchers to verify both successful operations and error conditions.

Technical Details

  • RSpec testing framework
  • CarrierWave uploader configuration
  • File system cleanup after tests
  • Mock cache_id generation
  • Dynamic range validation setup

Best Practices Demonstrated

The test suite exemplifies several testing best practices:

  • Isolated test contexts
  • Proper setup and teardown
  • Clear error message validation
  • DRY test structure using shared setup
  • Comprehensive edge case coverage

carrierwaveuploader/carrierwave

spec/uploader/file_size_spec.rb

            
require 'spec_helper'

describe CarrierWave::Uploader do
  let(:uploader_class) { Class.new(CarrierWave::Uploader::Base) }
  let(:uploader) { uploader_class.new }
  let(:cache_id) { '20071201-1234-1234-2255' }
  let(:test_file) { File.open(file_path('test.jpg')) }

  after { FileUtils.rm_rf(public_path) }

  describe '#cache!' do
    subject { uploader.cache!(test_file) }

    before { allow(CarrierWave).to receive(:generate_cache_id).and_return(cache_id) }

    describe "file size range" do
      before { allow(uploader).to receive(:size_range).and_return(range) }

      context "when not specified" do
        let(:range) { nil }

        it "doesn't raise an integrity error" do
          expect { subject }.not_to raise_error
        end
      end

      context "when below the minimum" do
        let(:range) { 2097152..4194304 }

        it "raises an integrity error" do
          expect { subject }.to raise_error(CarrierWave::IntegrityError, 'File size should be greater than 2 MB')
        end
      end

      context "when above the maximum" do
        let(:range) { 0..10 }

        it "raises an integrity error" do
          expect { subject }.to raise_error(CarrierWave::IntegrityError, 'File size should be less than 10 Bytes')
        end
      end

      context "when inside the range" do
        let(:range) { 0..100 }

        it "doesn't raise an integrity error" do
          expect { subject }.not_to raise_error
        end
      end
    end
  end
end