Check out https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md#custom-construction. I need to run now, but 'll update this answer with specifics for your situation in a couple of hours if you haven't already figured it out.
How can I replace a Tempfile with FactoryGirl?
-
28-06-2022 - |
문제
I'm testing a CSV uploader with rspec and I've saved a test file in /spec/fixtures that I pull into my tests with fixture_file_upload:
let(:file) do
fixture_file_upload(
Rails.root.join("spec/fixtures/chargeback_test.csv"),
"text/csv"
)
end
This works but I have the file path in each spec. I'd like to DRY out my code by putting this in a factory but I'm having trouble making FactoryGirl understand that I want a Tempfile back from FactoryGirl.create(:chargeback_csv)
.
I would have guessed the factory should look like this:
include ActionDispatch::TestProcess
FactoryGirl.define do
factory :chargeback_csv, :class => "Tempfile" do
ignore do
path { Rails.root.join("spec/fixtures/chargeback_test.csv") }
mime_type { "text/csv" }
binary { false }
end
initialize_with { fixture_file_upload(path, mime_type, binary) }
end
end
But, using this in my specs results in the following error:
Failure/Error: let(:file) { FactoryGirl.create(:chargeback_csv) }
NoMethodError:
undefined method `save!' for #<Tempfile:0x112fec730>
Solved! The save!
error is caused because FactoryGirl calls to_create
on new objects that it creates. Newer versions of FactoryGirl have an option skip_create
to avoid this error. I'm on an old version so I added to_create {}
to the factory and all my tests are green again.
include ActionDispatch::TestProcess
FactoryGirl.define do
factory :chargeback_csv, :class => "Tempfile" do
to_create {}
ignore do
path { Rails.root.join("spec/fixtures/chargeback_test.csv") }
mime_type { "text/csv" }
binary { false }
end
initialize_with { fixture_file_upload(path, mime_type, binary) }
end
end
해결책