factory_bot icon indicating copy to clipboard operation
factory_bot copied to clipboard

documentation support for ActiveStorage attachments

Open josh-m-sharpe opened this issue 1 year ago • 1 comments

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!

josh-m-sharpe avatar Dec 08 '22 21:12 josh-m-sharpe

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.

drewdeponte avatar May 22 '24 17:05 drewdeponte

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

formigarafa avatar Aug 08 '24 02:08 formigarafa