Julian
Julian

Reputation: 70

Rails Factory Bot with attachment - Working example

My rails app has a quite a few tests which I want to DRY (Don't repeat yourself) out. They at the moment are all filling out a form to generate a so called disbursement including a file attachment.

For my other models I used factory_bot Gem for this. I wanted to able to write something like Given there is a disbursement in my features, which then triggers a step calling factory_bot which I can easily copy from somewhere.

So far I have got:

FactoryBot.define do
  factory :disbursement do
    name { "Any" }
    date { Date.current }
    iban { "DE123456" }
  end
end

The problem is that a disbursement needs a file attachment physical_copy to be valid?. Reading the docs I don't find out how to create a file attachment in factory_bot. Any file created on the fly will do e.g. disbursement.txt with no content.

Upvotes: 1

Views: 60

Answers (1)

eugen
eugen

Reputation: 9226

Assuming you have a has_one_attached :physical_copy in your model, you can use something similar to this factory definition

FactoryBot.define do
  factory :disbursement do
    name { "Any" }
    date { Date.current }
    iban { "DE123456" }

    after(:build) do |record|
      record.physical_copy.attach(io: Rails.root.join("spec", "fixtures", "files", "disbursement.txt").open, filename: "disbursement.txt")
    end
  end
end

Upvotes: 1

Related Questions