Last Updated: February 25, 2016
· 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']] ='features/support/attachments/', row['Filename']), row['Type'])
      hash[row['Name']] = row['Content'].strip

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

Note: We set the accept headers in other steps definitions

The scenario then looks something like:

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!