* 对于代码块的测试
* 强大的测试helpers支持
* 简洁友好的输出
* 固定格式的测试结果输出
希望,你看完这些详尽解释的RSpec测试的好处能够,从传统的单元测试,开始接受Rspec方式的测试.而且,你会注意到选择RSpec测试,实际也并不比test/unit困难.
一. 对于代码块的测试
这是一种内置的测试支持,结构如下所示:
test "should have some behavior" do # test some behavior end
如果,你是在一个独立运行的Rails工程上,那么 点击这里,获得插件支持.另外,Rspec也同时支持Before do和after do的语法支持,用于在操作之前和之后执行.就像传统test/unit支持的setup和teardown(不太清楚setup和teardown和test/unit的关系的话请参考 Rails UnitTest 测试机制浅析),而且,你可以很容易把这些转变成块测试,如下例所示:
class Test::Unit::TestCase def self.setup(&block) define_method(:setup, &block) end def self.teardown(&block) define_method(:teardown, &block) end end
既然,最初,我们要通过我们的定义覆盖方法,现在,这些将被自带执行.
二.强大的测试helpers支持
测试helper如下:
# test/test_helper.rb require 'action_view/test_case' # test/helpers/application_helper_test.rb class ApplicationHelperTest < ActionView::TestCase test "should set page title with a block" do result = page_title do 'Heading' end assert_equal 'Heading
', result end end
如你所见,唯一需要做的就是继承ActionView::TestCase.下面是对于rake task的写法:
namespace :test do Rake::TestTask.new(:helpers) do |t| t.libs << "test" t.pattern = 'test/helpers/**/*_test.rb' t.verbose = true end Rake::Task['test:helpers'].comment = 'Run the helper tests in test/helpers' end
这样执行如下的rake命令就可以对helper进行测试:
$ rake test:helpers
三.简洁友好的specdoc方式测试输出
实际上,后面的两个Rspec的优势,我将在这一段中说明.假如你有两个个gems包colored和redgreen已经安装,那么使用Rspec你可以通过rake task测试并得到一个很好的输出.测试示例如下:
require 'colored' def banner(title, pad = 85) puts "\n#{title} ".ljust(pad, "*").yellow end def stripe puts ("-" * 84 + "\n").yellow end namespace :test do Rake::TestTask.new(:helpers) do |t| t.libs << "test" t.pattern = 'test/helpers/**/*_test.rb' t.verbose = true end Rake::Task['test:helpers'].comment = 'Run the helper tests in test/helpers' end namespace :tests do desc "Documents all tests in doc/TESTDOC" task :doc do File.open(Rails.root + '/doc/TESTDOC', 'w') do |file| Dir.glob('test/**/*_test.rb').each do |test| test =~ /.*\/([^\/].*)_test.rb$/ file.puts "#{$1.gsub('_', ' ').capitalize}:" if $1 File.read(test).map { |line| /test "(.*)" do$/.match line }.compact.each do |t| file.puts " - #{t[1]}" end file.puts end end end desc "Execute all application tests, plus TESTDOC" task :run do # document a list of all executed tests # (used to match up with requirements) Rake::Task['tests:doc'].invoke # unit tests banner "EXECUTING UNIT TESTS" Rake::Task['test:units'].invoke stripe # functional tests banner "EXECUTING FUNCTIONAL TESTS" Rake::Task['test:functionals'].invoke stripe # helper tests banner "EXECUTING HELPER TESTS" Rake::Task['test:helpers'].invoke stripe # integration tests banner "EXECUTING INTEGRATION TESTS" Rake::Task['test:integration'].invoke stripe # performance tests banner "EXECUTING APPLICATION BENCHMARKS" Rake::Task['test:benchmark'].invoke stripe end end

你只需要把这段测试代码,放到一个叫做"tests.rake"的文件,并在你的lib/tasks/目录下.你就可以通过在root目录下运行如下rake目录,进行测试,并得到良好的输出.这个rake tasks也会把测试记录输出到doc目录下的一个TESTDOC文件下.输出为你测工程进行的所有测试得到列表.