Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attaching ActiveStorage files in factorybot

I'm looking for a way to create factories for models which have active storage attachments

I attempted the method in this post

with my factory

factory :activity_fit_file, class: 'Activity' do
    association :user, factory: :user
    activity_type {:cycling}
    original_activity_log_file { fixture_file_upload("#{Rails.root}/spec/files/example_fit_file.fit") }
end

but I got this error

 NoMethodError:
   undefined method `fixture_file_upload' for #<FactoryBot::SyntaxRunner:0x000000000208c5f8>

What is the correct way to attach files in ActiveStorage?

like image 706
Qwertie Avatar asked Mar 13 '19 12:03

Qwertie


3 Answers

This solution works with rails 6:

factory :post do
  # ...
  after(:build) do |post|
    post.image.attach(
      io: File.open(Rails.root.join('test', 'fixture_files', 'test.jpg')),
      filename: 'test.jpg',
      content_type: 'image/jpeg'
    )
  end
end
like image 89
JoBalk Avatar answered Nov 11 '22 23:11

JoBalk


Try with Rack::Test::UploadedFile directly:

file { Rack::Test::UploadedFile.new('path', 'image/png') }
like image 25
s3tjan Avatar answered Nov 11 '22 22:11

s3tjan


Change your code to the following it will work.

include ActionDispatch::TestProcess
factory :activity_fit_file, class: 'Activity' do
    association :user, factory: :user
    activity_type {:cycling}
    original_activity_log_file { fixture_file_upload("#{Rails.root}/spec/files/example_fit_file.fit") }
end
like image 1
Umar Khan Avatar answered Nov 11 '22 21:11

Umar Khan