ActionDispatch::Http::UploadedFile.content_type 在 Rspec 测试中未初始化

2024-05-04

背景: 我有一个Book模型与一个cover_file通过我的 Rails 控制器之一使用上传的文件设置的属性。我正在使用 Rails v4.0.4。

Goal:我想测试是否仅保存具有特定内容类型的文件。我计划创建 Rspec 测试示例ActionDispatch::Http:UploadedFile设置不同的对象content_type属性。

Problem:当我初始化一个新的ActionDispatch::Http::UploadedFile with a content_type,它似乎没有被设置(请参阅下面的测试和输出,确认它为零)。看来我只能在 UploadedFile 初始化后用 setter 设置它。我在文档中没有看到任何提及此行为的信息,也找不到类似的问答,因此我非常感谢任何人帮助确定我做错了什么。谢谢!

Code:

describe Book do
  let(:book) {FactoryGirl.build(:book)}
  describe "Save" do
    context "with valid data" do
      before do
        cover_image = File.new(Rails.root + 'spec/fixtures/images/cover_valid.jpg')
        book.cover_file = ActionDispatch::Http::UploadedFile.new(tempfile: cover_image, filename: File.basename(cover_image), content_type: "image/jpeg")
        puts book.cover_file.content_type.nil?
        book.cover_file.content_type = "image/jpeg"
        puts book.cover_file.content_type
      end
      specify{expect(book.save).to be_true}
    end
  end
end

Output:

true
image/jpeg

我查看了 Rails 源文件UploadedFile类,我发现了问题。例如,对于 @content_type 属性,虽然 getter 和 setter 的命名符合预期 (.content_type), the initialize方法查找名为的属性type在选项哈希中。 @original_filename 也会发生同样的事情;初始化寻找filename代替original_filename。自 Rails 3 代码库以来似乎就是这种情况。

因此,如果我将上面的代码更改为以下内容,一切都会按预期进行:

book.cover_file = ActionDispatch::Http::UploadedFile.new(tempfile: cover_image, filename: File.basename(cover_image), type: "image/jpeg")

Rails/actionpack/lib/action_dispatch/http/upload.rb 的相关部分...

class UploadedFile
  # The basename of the file in the client.
  attr_accessor :original_filename

  # A string with the MIME type of the file.
  attr_accessor :content_type

  # A +Tempfile+ object with the actual uploaded file. Note that some of
  # its interface is available directly.
  attr_accessor :tempfile
  alias :to_io :tempfile

  # A string with the headers of the multipart request.
  attr_accessor :headers

  def initialize(hash) # :nodoc:
    @tempfile          = hash[:tempfile]
    raise(ArgumentError, ':tempfile is required') unless @tempfile

    @original_filename = encode_filename(hash[:filename])
    @content_type      = hash[:type]
    @headers           = hash[:head]
  end
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

ActionDispatch::Http::UploadedFile.content_type 在 Rspec 测试中未初始化 的相关文章

随机推荐