Testing Multipart Upload with Sinatra

2009-01-21

Here’s how we create multipart uploads in our test suite for testing with Sinatra 0.3, similar to the post_it test helper method:

def upload_it(path, params, rack_opts, file)
    @request = Rack::MockRequest.new(Sinatra.build_application)
    opts = normalize_rack_environment(opts)
    input = FiveRuns::Multipart::FileUpload.new(file, params)
    opts[:input] ||= input.to_s
    opts['CONTENT_TYPE'] = input.content_type
    opts['CONTENT_LENGTH'] = opts[:input].length
    @response = @request.request('POST', path, opts)
  end

You can use it as such:

filedata = Zlib::Deflate.deflate({'foo' => 'bar'}.to_json)
    other_params = {"pid"=>"20256"}
    upload_it "/apps/#{app.token}/processes.json", other_params, {}, StringIO.new(filedata)

Here’s the multipart helper: multipart.rb. I hope this saves someone a few hours of experimentation out there!