第5回 機能テスト
今回は、前回のテンプレートファイルの拡張子でコントローラを生成した際の副産物である機能テストについて。
test/functional/top_controller_test.rb の中身はこんな風になっています。
require File.dirname(__FILE__) + '/../test_helper'
class TopControllerTest < ActionController::TestCase
# Replace this with your real tests.
def test_truth
assert true
end
end
1.2.x の時にできた機能テストと比べて随分すっきりしています。かつては、初期状態で次のようになっていました。
require File.dirname(__FILE__) + '/../test_helper'
require 'top_controller'
# Re-raise errors caught by the controller.
class TopController; def rescue_action(e) raise e end; end
class TopControllerTest < Test::Unit::TestCase
def setup
@controller = TopController.new
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
end
# Replace this with your real tests.
def test_truth
assert true
end
end
top_controller を require したり、TopController を new したりといったコードは、すべての機能テストに共通のもので、ほとんど書き換えられる可能性がありません。こういうものをジェネレータに作らせるのは、DRY の原則に反します。Rails 2.0 は正しい方向に進化しているようです。
では、簡単なテスト駆動開発をやってみましょう。
require File.dirname(__FILE__) + '/../test_helper'
class TopControllerTest < ActionController::TestCase
def test_index
get :index
assert_response :success
message = assigns(:message)
assert_equal 'Hello World!', message
assert_template 'top/index'
assert_select 'title', 'Greeting'
end
end
テストを実行します。
ruby test/functional/top_controller_test.rb
予想通り、エラーが出ます。
Loaded suite test/functional/top_controller_test
Started
F
Finished in 0.143769 seconds.
1) Failure:
test_index(TopControllerTest)
[test/functional/top_controller_test.rb:8:in `test_index'
/usr/lib/ruby/gems/1.8/gems/activesupport-2.0.2/lib/active_support/testing/default.rb:7:in `run']:
<"Hello World!"> expected but was
<nil>.
1 tests, 2 assertions, 1 failures, 0 errors
インスタンス変数 @message に正しい値が入るように top_controller.rb を書き換えます。
class TopController < ApplicationController
def index
@message = 'Hello World!'
end
end
また、app/views/layout/application.html.erb を次のように書き換えます。
<html> <head> <title>Greeting</title> </head> (以下、略)
テストを実行すると、今度は通ります。
Loaded suite test/functional/top_controller_test Started . Finished in 0.067353 seconds. 1 tests, 4 assertions, 0 failures, 0 errors
なかなか、いい感じです。今日はここまでとしましょう。
(2008/01/19)
記事に関するご質問は、 hermes@oiax.jp までメールでお送りください。
ウェブサイト構築の発注先を検討されているお客様は、ご相談フォームをご利用ください。
- はじめに
- 第1回 インストール (2007/12/15)
- 第2回 新規アプリケーションの作成 (2007/12/16)
- 第3回 SQLite3 (2007/12/21)
- 第4回 テンプレートファイルの拡張子 (2007/12/22)
- 第5回 機能テスト (2008/01/19)
- 第6回 redirect_to と url_for (2008/02/24)
- 第7回 config/initializers ディレクトリ (2008/02/27)
- 第8回 Rails 1.2 の API ドキュメントを作る (2008/03/04)
- 第9回 helper :all (2008/05/05)

