[ACCEPTED]-Specifying Content Type in rspec-rack

Accepted answer
Score: 18

There's a way to do this described in this thread -- it's 1 a hack, but it seems to work:

@request.env["HTTP_ACCEPT"] = "application/json"
json = { ... data ... }.to_json
post :create, :some_param => json
Score: 18

In Rails 3, you can skip the header and 2 @request.env stuff and just add a format parameter to your 1 post call, e.g.:

post :create, format: :json, param: 'Value of Param'
Score: 10

A lot of frustration and variations and 1 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" => "bing@test.com"
Score: 5

First of all, you don't want to test the 7 built-in conversion of json to hash. Same 6 applies to xml.

You test controller with 5 data as hashes, not bothering wether it's 4 json, xml or from a html form.

But if you 3 would like to do that as an exercise, this 2 is a standalone ruby script to do play with 1 :)

require 'json'
url = URI.parse('http://localhost:3030/mymodels.json')
request = Net::HTTP::Post.new(url.path)
request.content_type="application/json"
request.basic_auth('username', 'password')  #if used, else comment out

hash = {:mymodel => {:name => "Test Name 1", :description => "some data for testing description"}}
request.body = hash.to_json
response = Net::HTTP.start(url.host, url.port) {|http| http.request(request)}
puts response

to switch to xml, use content_type="text/xml" and

request.body = "<?xml version='1.0' encoding='UTF-8'?><somedata><name>Test Name 1</name><description>Some data for testing</description></somedata>"
Score: 2

A slightly more elegant test is to use the 3 header helper:

header "HTTP_ACCEPT", "application/json"
json = {.... data ....}.to_json
post '/model1.json', json

Now this does exactly the 2 same thing as setting @env; it's just a bit 1 prettier.

Score: 1

The best way that I have found to test these 4 things is with request tests. Request tests 3 go through the full param parsing and routing 2 stages of Rails. So I can write a test like 1 this:

request_params = {:id => 1, :some_attribute => "some value"}
headers = {'Accept' => 'application/json', 'Content-Type' => 'application/json'}
put "/url/path", request_params.to_json, headers
expect(response).to be_success
Score: 1

I think that you can specify the headers 2 with headers param:

post '/model1.json', headers: {'Content-type': 'application/json'}

Following the Rspec documentation 1 of how provide JSON data.

Score: 0
@request.env["CONTENT_TYPE"] = "application/json"

OR pass in request

"CONTENT_TYPE" => "application/json"

0

More Related questions