Sunday, 15 May 2011

ruby - Unzip binary email attachment -



ruby - Unzip binary email attachment -

i have background job in rails app generates big csv file , sends attachment email message. manage size of email, i'm zipping csv before it's attached. works fine; have letter opener in development , can open zipped attachment , read data. i'm using "rubyzip" gem zipping.

the trick seems testing it. using rspec, can verify message has attachment , type of attachment application/x-zip-encoded, good. i'd unzip attachment , validate info within test, though, , that's proving more difficult. attachment object of type mail::part. if phone call attachment part, can info using part.body.raw_source, part.body.encoded or part.decode_body. (the first , 3rd identical.) part.body.encoding tells me body binary. when seek feed info zip::inputstream object (using zip::inputstream.open(part.body.raw_source) or of other info methods) argumenterror: string contains null byte.

how can open attachment , read info within rspec? have hunch there's decoding step need in here somewhere.

the errors look lot question, there's no reply there either.

the solution here little less ideal, works. had utilize mail service library write attachment file, utilize zip::file extract original info , verify it.

it 'has zip attachment' additional_fields = ["student_identifiers"] expect(message.attachments.size).to eq(1) message.attachments.first.tap |zip| expect(zip.content_type).to eq('application/x-zip-compressed') tmpfile_name = "tmp/#{zip.filename}" file.open(tmpfile_name, "w+b", 0644) { |f| f.write zip.decoded } csv = zip::file.open(tmpfile_name) |zip_file| entry = zip_file.glob('*.csv').first entry.get_input_stream.read end csv.split("\n").tap |rows| expect(rows.size).to be(2) rows.each |row| expect(csv.parse_line(row).size).to eq(dimensions_count) end end file.delete(tmpfile_name) end end

ruby ruby-on-rails-3 zip email-attachments

No comments:

Post a Comment