Read more

Carrierwave: How to attach files in tests

Emanuel
January 13, 2022Software engineer at makandra GmbH

Attaching files to a field that is handled by Carrierwave uploaders (or maybe any other attachment solution for Rails) in tests allows different approaches. Here is a short summary of the most common methods.

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

You might also be interested in this card if you see the following error in your test environment:

CarrierWave::FormNotMultipart:
You tried to assign a String or a Pathname to an uploader, for security reasons, this is not allowed.
If this is a file upload, please check that your upload form is multipart encoded.

Factory Bot

FactoryBot.define do

  factory :user do
    avatar { Rack::Test::UploadedFile.new(Rails.root.join('spec/fixtures/files/avatar.jpg')) }
  end

end

RSpec

RSpec has a helper method file_fixture Show archive.org snapshot :

describe User do

  let(:user) { build(:user, attachment: file_fixture('avatar.jpg').open) }

end

You can configure the directory where RSpec looks for fixture files:

RSpec.configure do |config|
  config.file_fixture_path = "spec/custom_directory"
end

Alternatives:

  • Rails.root.join('spec/fixtures/files/avatar.jpg').open('r')
  • Rails.root.join('spec/fixtures/files/avatar.jpg').read
  • File.open('spec/fixtures/files/avatar.jpg') (might only work if you run the command from the Rails root directory)

Cucumber

When('I attach the file {string} to {string}') do |path, field|
  attach_file(field, Rails.root.join('spec', 'fixtures', path))
end

Alternatives

Posted by Emanuel to makandra dev (2022-01-13 09:43)