class Rack::Test::UploadedFile

Wraps a Tempfile with a content type. Including one or more UploadedFile's in the params causes Rack::Test to build and issue a multipart request.

Example:

post "/photos", "file" => Rack::Test::UploadedFile.new("me.jpg", "image/jpeg")

Attributes

content_type[RW]

The content type of the “uploaded” file

original_filename[R]

The filename, not including the path, of the “uploaded” file

tempfile[R]

The tempfile

Public Class Methods

actually_finalize(file) click to toggle source
# File lib/rack/test/uploaded_file.rb, line 58
def self.actually_finalize(file)
  file.close
  file.unlink
end
finalize(file) click to toggle source
# File lib/rack/test/uploaded_file.rb, line 54
def self.finalize(file)
  proc { actually_finalize file }
end
new(content, content_type = 'text/plain', binary = false, original_filename: nil) click to toggle source

Creates a new UploadedFile instance.

@param content [IO, Pathname, String, StringIO] a path to a file, or an {IO} or {StringIO} object representing the

file.

@param content_type [String] @param binary [Boolean] an optional flag that indicates whether the file should be open in binary mode or not. @param original_filename [String] an optional parameter that provides the original filename if `content` is a StringIO

object. Not used for other kind of `content` objects.
# File lib/rack/test/uploaded_file.rb, line 30
def initialize(content, content_type = 'text/plain', binary = false, original_filename: nil)
  if original_filename
    initialize_from_stringio(content, original_filename)
  else
    initialize_from_file_path(content)
  end
  @content_type = content_type
  @tempfile.binmode if binary
end

Public Instance Methods

local_path()
Alias for: path
path() click to toggle source
# File lib/rack/test/uploaded_file.rb, line 40
def path
  tempfile.path
end
Also aliased as: local_path

Private Instance Methods

initialize_from_file_path(path) click to toggle source
# File lib/rack/test/uploaded_file.rb, line 70
def initialize_from_file_path(path)
  raise "#{path} file does not exist" unless ::File.exist?(path)

  @original_filename = ::File.basename(path)

  @tempfile = Tempfile.new([@original_filename, ::File.extname(path)])
  @tempfile.set_encoding(Encoding::BINARY) if @tempfile.respond_to?(:set_encoding)

  ObjectSpace.define_finalizer(self, self.class.finalize(@tempfile))

  FileUtils.copy_file(path, @tempfile.path)
end
initialize_from_stringio(stringio, original_filename) click to toggle source
# File lib/rack/test/uploaded_file.rb, line 65
def initialize_from_stringio(stringio, original_filename)
  @tempfile = stringio
  @original_filename = original_filename || raise(ArgumentError, 'Missing `original_filename` for StringIO object')
end