How to test file upload using factorygirl?

I want to test a model with a basic file upload that does not use a plugin (I think it was a bad idea at the time, but I know that I have to deal with a lot of existing documents).

The thing is, I want to check the size of the downloaded file, so I need to access the attribute temfile file, which is ActionDispatch :: Http :: UploadedFile

It works very well in my controllers, but I cannot find a way to make my factory pass.

Attachment Model:

attr_accessor :file # file_field_tag name
attr_accessible :file, :filename # store the filename in the db

before_save :upload_file

def upload_file
  if self.file && File.size(self.file.tempfile) < 10.megabytes
    puts self.file.class.inspect # see below
    File.open("#{Rails.root.to_s}/files/" + self.filename.to_s, 'wb') do |f|
      f.write(self.file.read)
    end
    ensure_file_presence
  end
end

FactoryGirl Attachment:

FactoryGirl.define do
  factory :attachment do
    filename 'anyfile.txt'
    file ActionDispatch::Http::UploadedFile.new(:tempfile => "#{Rails.root}/spec/fixtures/anyfile.txt", :filename => "anyfile.txt")
  end
end

When I run the tests, it FactoryGirl.build :attachmentwill succeed, but with createfail.

: self.file File.open, ActionDispatch::Http::UploadedFile, self.file.read: .

puts self.file.class.inspect
=> ActionDispatch::Http::UploadedFile

f.write(self.file.read) => NoMethodError: undefined method `read' for #<String:0x007ff50f70f6a0>

, , Rack::Test::UploadedFile fixture_file_upload, , tempfile 2 .

+4
1

. UpLoadedFile (:tempfile) , . String, String. File.new(), . , , . , !

FactoryGirl.define do
  factory :attachment do
    file ActionDispatch::Http::UploadedFile.new(:tempfile => File.new("#{Rails.root}/spec/fixtures/anyfile.txt"), :filename => "anyfile.txt")
  end
end
+12

All Articles