Using multipart/form-data when calling 'post' in tests

Hi,
Has anyone used ActionController::Integration::Session#post in their
integration tests to post multipart/form-data encoded parameters?
eg
my_session.post url , encoded_string , headers
where ‘headers’ includes the content-type and content-length.

Is there a library which will help generate this encoded string in ruby?
eg Net::HTTP::Post or something in rails?

I’ve started looking at RFC 2046, and various fragments people have
posted in the past - but I live in hope.

Regards,
Daniel

Daniel B. wrote:

Hi,
Has anyone used ActionController::Integration::Session#post in their
integration tests to post multipart/form-data encoded parameters?
eg
my_session.post url , encoded_string , headers
where ‘headers’ includes the content-type and content-length.

Is there a library which will help generate this encoded string in ruby?
eg Net::HTTP::Post or something in rails?

I’ve started looking at RFC 2046, and various fragments people have
posted in the past - but I live in hope.

Regards,
Daniel

Ok, to answer my own post in part:
If you’re going to write your own multipart/form-data encoding routine,
then remember these 2 things:

  1. prepend the boundary string with 2 dashes ‘–’ when using it
  2. don’t forget to append 2 dashes on the end of the last boundary

May as well post what I did:

In an integration test:

headers , encoded = encode_multipart(
{:id => xyz , :foo => ‘bar’ } ,
:image_param_name ,
image_file_path,
‘image/jpeg’
)
my_session.post ‘/admin/image_manager/update’,encoded,headers

Code:

EOL = “\015\012” # “\r\n”

Encode params and image in multipart/form-data.

def encode_multipart params,image_param,image_file_path,content_type
headers={}
parts=[]
boundary="----234092834029834092830498"
params.each_pair do |key,val|
parts.push %{Content-Disposition: form-data; }+
%{name="#{key}"#{EOL}#{EOL}#{val}#{EOL}}
end
image_part =
%{Content-Disposition: form-data; name="#{image_param}"; }+
%{filename="#{File.basename(image_file_path)}"#{EOL}}+
%{Content-Type: #{content_type}#{EOL}#{EOL}}
image_part << File.read(image_file_path) << EOL
parts.push image_part
body = parts.join("–#{boundary}#{EOL}")
body = “–#{boundary}#{EOL}” + body + “–#{boundary}–”+EOL
headers[‘Content-Type’]=“multipart/form-data; boundary=#{boundary}”
#headers[‘Content-Length’]=body.size
[ headers , body ]
end

Daniel