Sunday, November 4, 2007

Rails "What the...?'"s

I recently stumbled across 2 rails behaviors that have left me scratching my head. They both involve respond_to.
The first is how respond_to handles requests from Javascript changing the browsers location.
window.location='http://some/new/page';

Coming from Safari (and IE 6, I think) the request will be treated as a XHR. So this will cause your respond_to to return the .js action. I don't know if this is rails fault or the browser's but luckily you can fall back to request.xhr?
I had to replace my respond_to section with this:

render :template => 'items/new.rjs' if request.xhr?
render :template => 'items/new' unless request.xhr?

to get it to behave like I would expect across all browsers.

The other issue I had was during testing. I had a simple edit action:

def edit
@item = Item.find(params[:id])
respond_to do |wants|
wants.js
wants.html
end
end

Notice the order of the wants. The XHR is before the regular request. From my test I was calling
get :edit, :id => 1

and asserting
 assert_template 'edit'


This was failing because it was "expecting <"edit"> but rendering <"edit.rjs">". Hitting the action in a browser rendered the right result but the test failed. I had to reverse those two, so that the regular request was before the XHR request and then it worked. There seems to be first-come-first-serve functionality if the mime-type isn't specified.
I'll have to look into why the functional test "get" method doesn't set a mime-type.

No comments: