第5回 機能テスト
2008/01/19
今回は、前回のテンプレートファイルの拡張子でコントローラを生成した際の副産物である機能テストについて。
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
なかなか、いい感じです。今日はここまでとしましょう。
