File upload 如何使用factorygirl测试文件上传?

File upload 如何使用factorygirl测试文件上传?,file-upload,ruby-on-rails-3.2,factory-bot,File Upload,Ruby On Rails 3.2,Factory Bot,我想测试一个不使用插件的基本文件上传模型(我认为这在当时是个坏主意,但我知道我必须处理大量现有文档) 问题是我想测试上传文件的大小,所以我需要访问file的temfile属性,这是一个ActionDispatch::Http::UploadedFile 它在我的控制器中运行得很好,但我找不到如何使我的工厂通过 附件模型: attr_accessor :file # file_field_tag name attr_accessible :file, :filename # store the f

我想测试一个不使用插件的基本文件上传模型(我认为这在当时是个坏主意,但我知道我必须处理大量现有文档)

问题是我想测试上传文件的大小,所以我需要访问
file
temfile
属性,这是一个ActionDispatch::Http::UploadedFile

它在我的控制器中运行得很好,但我找不到如何使我的工厂通过

附件模型:

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.build:attachment
将成功,但使用
create
将失败

奇怪的观察:我在file.open之前显示了
self.file
类,它被视为
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>
put self.file.class.inspect
=>ActionDispatch::Http::UploadedFile
f、 write(self.file.read)=>NoMethodError:for的未定义方法“read”#

我读过其他帖子,建议我应该使用
Rack::Test::UploadedFile
fixture\u file\u upload
,但我无法让它工作,因为这两种解决方案中都不存在tempfile。

我看到了一个问题。UpLoadedFile(
:tempfile
)需要的是文件而不是字符串。根据您的观察,它从未变为字符串,您将其定义为字符串。您需要用
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

你让我高兴极了!太棒了!
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