From a7057b0800a8d047d18d0472a2f54e8c88e695d3 Mon Sep 17 00:00:00 2001 From: Matt Jankowski Date: Fri, 12 Sep 2008 17:51:01 -0400 Subject: [PATCH] add a should_respond_with_content_type macro for controller tests to check content type of response --- lib/shoulda/controller/helpers.rb | 4 ++++ lib/shoulda/controller/macros.rb | 10 ++++++++++ test/functional/posts_controller_test.rb | 10 ++++++++++ test/rails_root/app/controllers/posts_controller.rb | 4 ++++ 4 files changed, 28 insertions(+) diff --git a/lib/shoulda/controller/helpers.rb b/lib/shoulda/controller/helpers.rb index a6177971..67e8b48c 100644 --- a/lib/shoulda/controller/helpers.rb +++ b/lib/shoulda/controller/helpers.rb @@ -31,6 +31,10 @@ module ThoughtBot # :nodoc: variables_added }.map(&:to_s) + def response_content_type + @response.headers['Content-Type'] || @response.headers['type'] + end + def instantiate_variables_from_assigns(*names, &blk) old = {} names = (@response.template.assigns.keys - SPECIAL_INSTANCE_VARIABLES) if names.empty? diff --git a/lib/shoulda/controller/macros.rb b/lib/shoulda/controller/macros.rb index a0c8d314..7077d209 100644 --- a/lib/shoulda/controller/macros.rb +++ b/lib/shoulda/controller/macros.rb @@ -134,6 +134,16 @@ module ThoughtBot # :nodoc: end end + # Macro that creates a test asserting that the response content type was 'content_type'. + # Example: + # + # should_respond_with_content_type 'application/rss+xml' + def should_respond_with_content_type(content_type) + should "respond with content type of #{content_type}" do + assert_match content_type, response_content_type, "Expected #{content_type} but was actually #{response_content_type}" + end + end + # Macro that creates a test asserting that the controller rendered the given template. # Example: # diff --git a/test/functional/posts_controller_test.rb b/test/functional/posts_controller_test.rb index e5d625e8..21833c91 100644 --- a/test/functional/posts_controller_test.rb +++ b/test/functional/posts_controller_test.rb @@ -48,6 +48,16 @@ class PostsControllerTest < Test::Unit::TestCase should_assign_to :user, :posts should_not_assign_to :foo, :bar end + + context "viewing posts for a user with rss format" do + setup do + get :index, :user_id => users(:first), :format => 'rss' + end + should_respond_with :success + should_respond_with_content_type 'application/rss+xml' + should_assign_to :user, :posts + should_not_assign_to :foo, :bar + end end end diff --git a/test/rails_root/app/controllers/posts_controller.rb b/test/rails_root/app/controllers/posts_controller.rb index 3a7d5783..ea39925d 100644 --- a/test/rails_root/app/controllers/posts_controller.rb +++ b/test/rails_root/app/controllers/posts_controller.rb @@ -8,6 +8,10 @@ class PostsController < ApplicationController respond_to do |format| format.html # index.rhtml format.xml { render :xml => @posts.to_xml } + format.rss do + headers['Content-Type'] = 'application/rss+xml' + head :ok + end end end