Setting Content-Type header for RSpec and Rails-API

Peter Brown picture Peter Brown · Dec 18, 2012 · Viewed 9k times · Source

I'm using the rails-api gem to build a web service and want to test my API with RSpec. Every request I make, regardless of the HTTP method has the CONTENT_TYPE header set as "application/x-www-form-urlencoded". This isn't really a problem until I try to use wrap_parameters in my controller and it's not have any affect on the params hash:

class ApplicationController < ActionController::API
  include ActionController::ParamsWrapper
end

class ProjectsController < ApplicationController
  wrap_parameters :project, include: [:name]
  # ...
end

This hack no longer works (@request is nil), and none of the other Stack Overflow posts I found work either.

If I make the following request in my RSpec test:

put "/projects/1.json", {name: 'Updated Project 1'}

and put a debugger in my controller I get:

(rdb:1) p params
    { "name"=>"Updated Project 1",
  "action"=>"update",
  "controller"=>"projects",
  "id"=>"5539bbd9-010c-4cfb-88d3-82dadbc99507",
  "format"=>"json"
}

(rdb:1) p request.content_type
"application/x-www-form-urlencoded"

I'm expecting to see something like this for the params hash (note the addition of the project key):

{ "name"=>"Updated Project 1",
  "action"=>"update",
  "controller"=>"projects",
  "id"=>"5539bbd9-010c-4cfb-88d3-82dadbc99507",
  "format"=>"json",
  "project" => {"name" => "Updated Project 1"}
}

Is it possible to set the content type header using just RSpec? Or do I have have to use rack/test for this functionality?

Answer

VelLes picture VelLes · Mar 26, 2013

A lot of frustration and variations and that's what worked for me. Rails 3.2.12 Rspec 2.10

 @request.env["HTTP_ACCEPT"] = "application/json"
 @request.env["CONTENT_TYPE"] = "application/json"
 put :update, :id => 1, "email" => "[email protected]"

wrap_parameters seems to be working declared this way

wrap_parameters User, format: :json

being used for User model