测试驱动开发
测试驱动开发(TDD)是一种软件开发的方法,它建议你应该为一些代码写测试,然后继续写一些真正的代码使得它们能通过测试.
TDD 已经被许多公司和开发者所拥抱,尤其是在 Rails 的世界中.随着世界的推移,一些人就会意识到TDD可以通过单元测试可以更好的应用到静态测试.驱动测试是一个测试过程,可以使得应用软件的单元的进行单独测试过程,比如一个或者更多的模块或过程,用测试集合来测试他们能否正确的被应用.
单元测试验证了单个的模块在隔离的情况下是正确的.促进增量开发和重构,能够更早的发现bug,许多应用是数据驱动的,问题会在特定的数据环境,配置和真正的代码交叉的情况下发现的.这种情况下,尽管模型可以有效的进行单元测试,应用的整体功能测试,使用真实的数据来充分的测试代码.
自从Rails框架成立之处测试就已经包含在其中了.某种方式上,我们可以认为TDD是Rails DNA的一部分.因为每个应用和数据库交互,Rails依赖一个已经填入了一些简单的数据库进行足够的测试.功能测试也尽可能的用浏览器请求模拟,这样你就不需要在你的浏览器中点击你的应用来确保它能工作.
Rails 在每一个新的Rails项目用rails new application_name命令创建的时候,会创建一个叫做"test/"测试文件夹.这个测试文件夹结构固定好了,'models'目录包含了模型的测试,'controllers'目录包含了控制的测试,'integration'目录包含涉及与控制器交互的测试.
在'test'目录下还有其它的文件夹.'fixtures'文件夹包含了测试数据,'test'文件夹下的'test_helper.rb'文件包含了Rails应用默认的测试配置.
党我们的控制器生产的时候,相应的在测试类会在'test/controllers/say_controller_test.rb'.默认这个文件包含了测试声明,这个声明成功的调用默认方法:
require 'test_helper'
class SayControllerTest < ActionController::TestCase
test "should get hello" do
get :hello
assert_response :success
end
end
运行应用的所有测试(这个例子中,仅仅只有一个),在终端窗口中运行rake test:
$ rake test
# Running:
.
Finished in 0.045843s, 21.8136 runs/s, 21.8136 assertions/s.
1 runs, 1 assertions, 0 failures, 0 errors, 0 skips
这个测试运行并且成功了.多么令人兴奋啊,让我们来多写点吧!
第一个我们要写的是断言如果没有参数传递给"hello"方法,回应应该是"{"hello":"Rails!"}":
require 'test_helper'
class SayControllerTest < ActionController::TestCase
test "should get hello" do
get :hello
assert_response :success
end
test "should say hello rails in json" do
get :hello
assert_equal "{\"hello\":\"Rails!\"}", @response.body
end
接着来运行它:
$ rake test
# Running:
.
Finished in 0.011128s, 179.7268 runs/s, 179.7268 assertions/s.
2 runs, 2 assertions, 0 failures, 0 errors, 0 skip
现在我们要确定如果传递一个用户参数,对应的反应应该是{"hello":"<user!>"}":
require 'test_helper'
class SayControllerTest < ActionController::TestCase
test "should get hello" do
get :hello
assert_response :success
end
test "should say hello rails in json" do
get :hello
assert_equal "{\"hello\":\"Rails!\"}", @response.body
end
test "should say hello john in json" do
get(:hello, {'user' => "John"})
assert_equal "{\"hello\":\"John!\"}", @response.body
end
end
最后一次运行它:
$ rake test
# Running:
.
Finished in 0.015381s, 195.0458 runs/s, 195.0458 assertions/s.
3 runs, 3 assertions, 0 failures, 0 errors, 0 skips
测试运行完了,我们已经验证了代码表现的如我们预期的一样.我个人相信TDD,尽管它还有些争议,有些开发者已写了一些博客来声称TDD已死.我们将保持为我们的代码编写简单的测试的习惯,但是如果你认为这个训练是枯燥的,你可以选择忽略测试这部分.







网友评论