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 UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
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)