Testing different content types with rspec

Rspec ( rather it's dependency ZenTest ) does not currently support content type headers for Controller testing using the Rspec on Rails plugin.

Monkey patch Test::Rails::ControllerTestCase

class Test::Rails::ControllerTestCase

  %w(get put post head delete).each{|m| define_method(m.to_sym) do |*args|
      @request.env['REQUEST_METHOD'] = m.upcase
      @request.env['CONTENT_TYPE'] = Mime::EXTENSION_LOOKUP[(args[2].nil? ? 'html' : args[2].to_s )]
      process( args[0], args[1] || {} )  
    end
  }   

end

Add the above to your Spec helper (spec/spec_helper.rb) after

require 'rspec_on_rails'

and before your Test::Rails::Testcase definition.

Examples

For the sake of saving keystrokes and taking the ability to add your own custom MIME Type extensions in consideration, pass the MIME Type extension (xml, html, js, rss, atom, yaml etc.) as the third argument.Defaults to html if not given.

  get :index, {:locale => 'en'}           #requests HTML content
  get :index, {:locale => 'en'}, :html #requests HTML content
  get :index, {:locale => 'en'}, :xml  #requests XML content
  get :index, {:locale => 'en'}, :js     #requests Javascript content

About this entry