thoughtbot / factory_bot

A library for setting up Ruby objects as test data.
https://thoughtbot.com
MIT License
7.91k stars 2.6k forks source link

documentation support for ActiveStorage attachments #1559

Open josh-m-sharpe opened 1 year ago

josh-m-sharpe commented 1 year ago

Problem this feature will solve

As ActiveStorage is a proper part of rails now, it would be nice if factory bot provided documentation for attaching a file as an active storage attachment. (I'd submit a PR, but candidly I haven't figure out the correct way to make all the things play nicely.)

Thanks!

drewdeponte commented 3 months ago

I just used the before(:create) hook to tie in and do it. See the following.

FactoryBot.define do
  factory :partner_state_page, class: 'PartnerStatePage' do
    before(:create) do |page, context|
      page.hero_image.attach(io: File.open(File.join(File.dirname(__FILE__), '../fixtures/Green_Lantern.png')), filename: 'Green_Lantern_Hero.png')
    end
  end
end

Hope that helps.

formigarafa commented 1 month ago

And in case you need to have a blob ready to attach you can use something like:

FactoryBot.define do
  factory :blob_file, class: "ActiveStorage::Blob" do
    transient do
      filename { Faker::File.file_name ext: "txt", dir: nil, directory_separator: nil }
      content { Faker::ChuckNorris.fact }
      io { StringIO.new(content) }
    end

    initialize_with do
      ActiveStorage::Blob.build_after_unfurling(io: io, filename: filename)
    end

    after(:create) {|blob, context| blob.upload_without_unfurling(context.io) }
  end
end