Mike Perham

On Ruby, software and the Internet

Testing Multipart Upload with Sinatra

January 21st, 2009 · 2 Comments

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!

Tags: Ruby

2 responses so far ↓

  • 1 rick // Mar 15, 2009 at 8:22 pm

    Sir, this does not work at all. It’s not current for the latest version of Sinatra. I’ll try to post a working version once I figure it out (though something like this should really exist in Rack if it doesn’t already).

  • 2 mperham // Mar 15, 2009 at 8:38 pm

    Yeah, I noted this is for Sinatra 0.3. No guarantees for other versions, especially since 0.9 was such a large change.

Leave a Comment