ウェブサービスを作っています。

拡張子付きリクエストのテスト方法

http://example.com/articles.rss

のようなリクエストをテストする方法です。


config/routes.rb

map.resources :articles

app/controllers/articles_controller.rb

class ArticlesController < ApplicationController
  def index
    respond_to do |format|
      format.html do
        redirect_to 'http://example.com'
      end

      format.rss do
        render :text => 'rss'
      end
    end
  end
end

という前提。


やり方は、拡張子に対応した MIME タイプを request.env['HTTP_ACCEPT'] で指定すれば OK です。

describe ArticlesController do
  def request_rss
    request.env['HTTP_ACCEPT'] = 'application/rss+xml'
  end

  describe 'GET /articles/index' do
    describe 'で、rss を取得するとき' do
      before do
        request_rss
      end

      it 'は、レスポンスが成功すること' do
        get :index
        response.should be_success
        response.should_not redirect_to('http://example.com')
      end
    end
  end
end


拡張子と MIME タイプの対応は、

で定義された関係が使用されるのだと思います。(未調査)