Rspec on Railsで、controllerで使うライブラリのテストをする方法

環境

ライブラリ


例えば、includeしたら、before_filterで、params[:price]の末尾に"円"を追加するライブラリのテストを書く場合

# -*- encoding: utf-8 -*-
module TestLib
  # includeされたら、before_filterを追加する
  def self.included(klass)
    klass.class_eval do
      before_filter :add_unit
    end
  end
  # "円"を追加する
  def add_unit
    params['price'] = "#{params['price']}"
  end
end

テスト


テストはこんな感じになる

# -*- encoding: utf-8 -*-
require File.dirname(__FILE__) + '/../spec_helper'

# テスト用のコントローラ
class TestLibController < ApplicationController
  include TestLib
  def index
    response.content_type = 'text/html'
    render :text => params['price']
  end
end

# :type => :controller でcontrollerのspec_helperを使えるようにする
# * controllerディレクトリのテストの場合は勝手にやってくれる
describe TestLibController, :type => :controller do
  before :all do
    # テスト用のroutesを追加
    AppLibTest::Application.routes.draw do
      match 'index', :to => 'test_lib#index'
    end
  end

  # routesの初期化
  after(:all){ Rails.application.reload_routes! }

  subject do
    get :index, :price => '100'
    response
  end
  it{ subject.should be_success }
  its(:body){ '100円' }
end

ポイント

  • テストを実行するためのコントローラを作る
  • describeで明示的に、コントローラのテストであることを、rspec側に教える
  • before :all で、Application.routesでテスト用コントローラのルーティングを切る
  • after :all で、ルーティングを初期化する


gistにコード上げてみた