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?
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
Try with Rack::Test::UploadedFile directly:
file { Rack::Test::UploadedFile.new('path', 'image/png') }
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With