Ruby 1.9 Rspec 风格 Unit Test MiniTest::Spec介绍
MiniTest是1.9后加到ruby标准库里的。其中,有几个部分当在1.9中写
require 'test/unit'时,会兼容的把MiniTest:Unit载入,然而MiniTest::Unit只是增加了assertions
require 'test/unit'class TestArray < Test::Unit::TestCase def test_array_can_be_created_with_no_arguments assert_instance_of Array, Array.new end def test_array_of_specific_length_can_be_created assert_equal 10, Array.new(10).size endend
require 'minitest/spec'require 'minitest/autorun'describe Array do it "can be created with no arguments" do Array.new.must_be_instance_of Array end it "can be created with a specific size" do Array.new(10).size.must_equal 10 endend
require 'minitest/autorun' class TestMeme < MiniTest::Unit::TestCase def setup @meme = Meme.new end def test_that_kitty_can_eat assert_equal "OHAI!", @meme.i_can_has_cheezburger? end def test_that_it_will_not_blend refute_match /^no/i, @meme.will_it_blend? end end
require 'minitest/autorun' describe Meme do before do @meme = Meme.new end describe "when asked about cheeseburgers" do it "must respond positively" do @meme.i_can_has_cheezburger?.must_equal "OHAI!" end end describe "when asked about blending possibilities" do it "won't say no" do @meme.will_it_blend?.wont_match /^no/i end end end#这里是我说的那个,还是不支持所有测试before :all
obj.must_be(operator, expected) # for example, 10.must_be :< , 11obj.must_be_close_to # the equivalent of assert_in_deltaobj.must_be_empty - Fails unless obj.empty?obj.must_be_instance_of(klass) # Fails unless obj.class == klassobj.must_be_kind_of(klass) # Fails unless obj is of class klass or klass is one of its superclasses.obj.must_be_nilobj.must_be_same_as $ tests for true object equalitylambda {}.must_be_silentobj.must_be_within_deltaobj.must_be_within_epsilonobj.must_equal(other) # Does a ==/eql? comparison between two objects.obj.must_include(other)obj.must_match(regex) # A regular expression match, e.g. "hello".must_match /w+/lambda {}.must_output(stdout, [stderr..]) # The block should have certain output on stdout or stderr. Set stdout to nil just to check stderr.lambda {}.must_raise(exception)obj.must_respond_to(message)obj.must_throw(sym)wont_bewont_be_emptywont_be_instance_ofwont_be_kind_ofwont_be_nilwont_be_same_aswont_equalwont_includewont_matchwont_respond_to
require 'rake/testtask'Rake::TestTask.new do |t| t.libs.push "lib" t.test_files = FileList['test/*_test.rb'] t.verbose = trueend
## optionally run benchmarks, good for CI-only work! require 'minitest/benchmark' if ENV["BENCH"] class TestMeme < MiniTest::Unit::TestCase # Override self.bench_range or default range is [1, 10, 100, 1_000, 10_000] def bench_my_algorithm assert_performance_linear 0.9999 do |n| # n is a range value @obj.my_algorithm(n) end end end
#或者放到spec里 describe Meme do if ENV["BENCH"] then bench_performance_linear "my_algorithm", 0.9999 do |n| 100.times do @obj.my_algorithm(n) end end end end
TestBlah100100010000 bench_my_algorithm 0.006167 0.079279 0.786993 bench_other_algorithm 0.061679 0.792797 7.869932