Back to Repositories

Testing CarrierWave Uploader Mounting Functionality in carrierwaveuploader/carrierwave

This test suite validates core mounting functionality in CarrierWave, focusing on uploader initialization and model associations. It ensures proper handling of file attachments and uploader instances across different mounting scenarios.

Test Coverage Overview

The test suite covers essential mounting capabilities of CarrierWave, including model associations, mount point naming, and multiple file handling.

  • Model association testing through #model method
  • Mount point identification via #mounted_as
  • Multiple file upload indexing verification
  • Edge cases for different file types and multiple attachments

Implementation Analysis

The testing approach utilizes RSpec’s let blocks for efficient test setup and context isolation. The implementation leverages doubles for model mocking and stub files for attachment simulation.

Key patterns include:
  • Test isolation using let blocks
  • Mock objects for model interaction
  • Stub file creation for attachment testing
  • Clean teardown with FileUtils

Technical Details

  • Testing Framework: RSpec
  • Mocking Library: RSpec doubles
  • File System Cleanup: FileUtils
  • Test Setup: spec_helper integration
  • Fixture Handling: stub_file helper method

Best Practices Demonstrated

The test suite exemplifies clean testing practices with proper isolation and setup/teardown handling.

  • Isolated test contexts using RSpec describe blocks
  • Efficient resource cleanup after tests
  • Clear test case organization
  • Descriptive test naming conventions
  • Proper mock object usage

carrierwaveuploader/carrierwave

spec/uploader/mountable_spec.rb

            
require 'spec_helper'

describe CarrierWave::Uploader do
  let(:uploader_class) { Class.new(CarrierWave::Uploader::Base) }
  let(:uploader) { uploader_class.new }

  after { FileUtils.rm_rf(public_path) }

  describe '#model' do
    let(:model) { double('a model object') }
    let(:uploader) { uploader_class.new(model) }

    it "is remembered from initialization" do
      expect(uploader.model).to eq(model)
    end
  end

  describe '#mounted_as' do
    let(:model) { double('a model object') }
    let(:uploader) { uploader_class.new(model, :llama) }

    it "is remembered from initialization" do
      expect(uploader.mounted_as).to eq(:llama)
    end
  end

  describe '#index' do
    let(:model) { Class.new.send(:extend, CarrierWave::Mount) }
    let(:instance) { model.new }
    before do
      model.mount_uploaders(:images, uploader_class)
      instance.images = [stub_file('test.jpg'), stub_file('bork.txt')]
    end

    it "returns the current index in uploaders" do
      expect(instance.images.map(&:index)).to eq [0, 1]
    end
  end
end