MiniTest 是在 ruby 1.9 版本中引入的,是 Test::Unit 的改进版本并且兼容 Test::Unit.
废话不多说,直接来例子吧 1.一个简单的类
#vim people.rb
class People
def name
"towonzhou"
end
end
2.用 MiniTest 测试了
#vim people_test.rb
require 'minitest/autorun'
require './people'
class TestPeople < Minitest::Test
def setup
@people = People.new
end
def test_name_is_towonzhou
assert_equal "towonzhou", @people.name
end
end
直接运行 ruby people_test.rb
即可得到结果
Run options: --seed 10922
# Running:
.
Finished in 0.001302s, 768.0492 runs/s, 768.0492 assertions/s.
1 runs, 1 assertions, 0 failures, 0 errors, 0 skips
ok 搞定。
前面说过 MiniTest 也支持期望式的语法,语法跟 rspec 很像,也是用 describe 和 it 代码块。
#vim people_spec.rb
require 'minitest/autorun'
require './people'
describe People do
before do
@people = People.new
end
describe "#name" do
it "returns the name of the people" do
@people.name.must_equal "towonzhou"
end
end
end
运行结果如下:
Run options: --seed 38156
# Running:
.
Finished in 0.001585s, 630.9148 runs/s, 630.9148 assertions/s.
1 runs, 1 assertions, 0 failures, 0 errors, 0 skips
列出几个常用的方法吧
ASSERTION EXPECTATION
assert_equal must_equal
assert_instance_of must_be_instance_of
assert_nil must_be_nil
assert_raises must_raise
更多方法参见Assertions和Expectations
下面是大家关心的怎么在 rails 中应用呢 只需要几步就可以了
gem "minitest-rails"
bundle install
rails generate minitest:install
3.在config/application.rb
设置一下
config.generators do |g|
g.test_framework :minitest, spec: true
end
搞定了,当你再次运行 rails g 命令的时候就会生成 minitest 文件了
以上的几个例子在github