Last Updated: February 25, 2016
·
3.271K
· gvarela

Testing multipart posts with cucumber-api-steps

At Mode Set we use @jayzes's cucumber-api-steps to test and document APIs that we create for client projects. We recently need to test image uploading via a multipart form post. Rack::Test makes this pretty trivial. We defined a custom step below.

Given( /^(?:|I )send a multipart (POST|PUT) request (?:for|to) "([^"]*)" with:/) do |verb, path, body|
  body = body.hashes
  request = body.inject({}) do |hash, row|
    if row['Filename'].present?
      hash[row['Name']] = Rack::Test::UploadedFile.new(Rails.root.join('features/support/attachments/', row['Filename']), row['Type'])
    else
      hash[row['Name']] = row['Content'].strip
    end
    hash
  end

  page.driver.send(verb.downcase.to_sym, path, request)
end

Note: We set the accept headers in other steps definitions

The scenario then looks something like:

@json
Scenario: As a patient I want to attach an image to a message
  When I send a multipart POST request to "/api/doctors/1/messages" with:
   | Name                | Content     | Filename      | Type       |
   | message[body]       | lorem ipsum |               |            |
   | message[attachment] |             | face-itch.jpg | image/jpeg |

There you have it test your API with file uploads!