Testing JSON stuff

Hi,

I have some code in a controller that receives JSON requests in this
sort of format:

http://www.json.org/JSONRequest.html

However, I am not finding a way to test that, since:

  1. post() seems to insist on sending key-value pairs.

  2. I’m not sure what to post to trigger the format.js in respond_to

Any suggestions?

Thankyou,
Dave

First of all, json is usually only sent to javascript apps on web
browsers do to lack of standard xml support. Maybe you should consider
sending xml to your rails app.

Secondly, I think you mean something like this:

respond_to do |format|
format.xml { render :xml => @your_object.to_xml }
format.json { render :json => @your_object.to_json }
format.yaml { render :yaml => @your_object.to_yaml }
end

On Sep 17, 11:59 am, “[email protected][email protected]

First of all, json is usually only sent to javascript apps on web
browsers do to lack of standard xml support. Maybe you should consider
sending xml to your rails app.

Hi, thanks - it’s not a bad idea, but we need to handle json in our
rails app, and I want to be able to test it, of course.

Secondly, I think you mean something like this:

respond_to do |format|
format.xml { render :xml => @your_object.to_xml }
format.json { render :json => @your_object.to_json }

Oops, of course. Doesn’t fix the problem though, I still get a test
failure when doing:

post(:create, {'foo' => 'bar'}, {"Content-Type" => "application/

json"})
assert_equal @response.body, “{good: “ok”}”

against

  format.json {
    ok = { :good => 'ok' }
    render :json => ok.to_json
  }
   format.yaml { render :yaml => @your_object.to_yaml }
 end

Thanks,
Dave

Ok… I think I figured it out. The problem is that I needed an
integration test, not a functional test. The way the two work seems to
be subtly different. This works ok:

def test_create
open_session do |sess|
sess.post(’/resource/create.js’, ‘{answer: 42}’, {“Content-type”
=> “application/json”})
assert_equal “{answerplusone: 43}”, sess.response.body
end
end

With this:

def create
respond_to do |format|
format.html {
render :text => ‘hello world’
}
format.js {
ok = { :good => ‘ok’ }
render :json => ok.to_json
}
end
end

Well… at least in the sense of sending the right stuff and getting
the right section of code back.

Progress… sort of. But I’m even more suspicious of this testing
framework now:

post(:create, {:q => 'foo'}, {"Content-Type" => "application/

json"})
assert_equal “{good: “ok”}”, @response.body

However, in the controller, I have:

logger.warn "INFO: " + request.env.inspect
logger.warn "HEADERS: " + headers.inspect

And I get:

INFO: {“REMOTE_ADDR”=>“0.0.0.0”, “REQUEST_URI”=>"/resource/create?
q=foo", “SERVER_PORT”=>80, “REQUEST_METHOD”=>“POST”}
HEADERS: {“cookie”=>[], “Cache-Control”=>“no-cache”}

  1. The URI should not include q=foo - those should be passed as part
    of the POST, no?

  2. What the heck happened to my Content-Type header?!

This isn’t making much sense at all.

Thanks,
Dave