Test::Unit and Raw Request Body

In testing a Rails 3 web API with Test::Unit, I found myself digging through documentation to POST raw JSON to a controller action. After a bit of searching, I decided to take a look at the source code for ActionDispatch::Request’s raw_post. Below is the end result:

test "should create joke" do
  @request.env['RAW_POST_DATA'] = {
    :body => 'Why did the chicken cross the road?'
  }.to_json
  @request.env['CONTENT_TYPE'] = 'application/json'
  post :create

  assert_response :success
  assert_not_nil @response.headers['Location']
end

My name is Hector Castro and I am a developer located in Philadelphia, PA. You can see what I'm working on at GitHub. I have a profile on Stack Overflow Careers, and if you're old-fashioned, a resume.

You can get in contact with me via Twitter or E-mail.