Ruby on Rails 2.0 日记
第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 ,创建 TopController 的实例等代码,在所有的功能测试里都是共同的东西,几乎没有改变的可能性。让发生器生成这些东西的话,就违反了 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)
- 前言
- 第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)

