[rspec-users] rendering xml with haml through render_template is invalid

Stephen Bannasch stephen.bannasch at deanbrook.org
Thu Sep 8 21:52:01 EDT 2011


I have some controller tests for validity of restful XML responses.

I'm using haml to generate the xml.

When I test externally with curl the response is well-formed XML.

However when I test the controllers with rspec2 the response is invalid XML.

The following code is part of an rspec shared_example:

   it "renders the requested #{model_ivar_name_lambda.call} as otml without error" do
     @model_class.stub!(:find).with("37").and_return(@model_ivar)
     get :show, :id => "37", :format => 'otml'
     response.should render_template(:show)

The response body includes both well formed and invalid XML:

For example running this test:

   bin/rspec spec/controllers/embeddable/open_responses_controller_spec.rb

I've extracted part of the response below to show the <OTCssText> element is not closed and is invalid XML

   <cssBlocks>
     <OTCssText local_id='otml_css' src='/stylesheets/otml.css'>
   </cssBlocks

Here's the same extract showing valid XML when the request travels through the entire app:

   curl http://localhost:3000/embeddable/open_responses/3.otml

   <cssBlocks>
     <OTCssText local_id='otml_css' src='/stylesheets/otml.css' />
   </cssBlocks>

Haml normally uses the Rails 3 default format of :html5 for rendering which will render complete elements without a '/>' ending.

However it seems that when going through the whole stack the fact that we've registered 'otml' as a 'text/xml' mime_type causes 
Haml to use the :xhtml format.

   Mime::Type.register "text/xml", :otml

However if I specifically set the Haml format to :xhtml in the spec test like this:

   it "renders the requested #{model_ivar_name_lambda.call} as otml without error" do
     Haml::Template.options[:format] = :xhtml
     @model_class.stub!(:find).with("37").and_return(@model_ivar)
     get :show, :id => "37", :format => 'otml'
     assigns[@model_ivar_name].should equal(@model_ivar)
     response.should render_template(:show)

Now the response is well-formed XML.

But this is disturbing because I am not doing that in the application.

It may be a problem with rspec, rspec-rails, haml or the ActionController::TestResponse rspec delegates to ... ???



More information about the rspec-users mailing list