Shrine: Help with FactoryGirl

Created on 10 Jan 2017  路  4Comments  路  Source: shrinerb/shrine

I'm trying for a few hours to make this work. I will resort to the supreme wisdom for help :confused:. I get the error below when try seed data:

ActiveRecord::RecordInvalid: Avatar isn't of allowed type: ["image/jpg", "image/jpeg", "image/png"]

I try upload a file with factory, but the mime type not exists.

FactoryGirl.define do
  factory :user do
    ...
    avatar { File.open(File.join(Rails.root, 'spec/fixtures/avatar.jpg')) }
    ...
  end
end

Have a way to do this?

Most helpful comment

Don't include ActionDispatch::TestProcess. It has some nasty consequences.

Proper solution is to use Rack::Test::UploadedFile directly in the factory (what fixture_file_upload essentially does anyway):

file { Rack::Test::UploadedFile.new('spec/factories/test.png', 'image/png') }

All 4 comments

Solved!

The answer is here.

include ActionDispatch::TestProcess

FactoryGirl.define do
  factory :user do
    ...
    avatar { fixture_file_upload(Rails.root.join('spec', 'fixtures', 'avatar.jpg'), 'image/jpg') }
    ...
  end
end

By default Shrine will take MIME type from the #content_type property of the given file. The files uploaded to the app have that property (it's populated with the value of the "Content-Type" header), but raw File objects don't have it, so in that case MIME type will be nil and the validation will fail.

To fix this just load the determine_mime_type plugin, which can determine the MIME type from file content or file extension.

Much better, thanks for the great tip!

Don't include ActionDispatch::TestProcess. It has some nasty consequences.

Proper solution is to use Rack::Test::UploadedFile directly in the factory (what fixture_file_upload essentially does anyway):

file { Rack::Test::UploadedFile.new('spec/factories/test.png', 'image/png') }
Was this page helpful?
0 / 5 - 0 ratings

Related issues

jakehockey10 picture jakehockey10  路  6Comments

musaffa picture musaffa  路  7Comments

brunowego picture brunowego  路  4Comments

thebravoman picture thebravoman  路  8Comments

nynhex picture nynhex  路  6Comments