测试 初次使用 MiniTest

towonzhou · 2014年11月04日 · 6577 次阅读

MiniTest 是在 ruby 1.9 版本中引入的,是 Test::Unit 的改进版本并且兼容 Test::Unit.

  1. MiniTest 支持 assertions, 并且兼容 Test::Unit, 如果你的测试用例是用 Test::Unit 写的,那么可以平滑的过渡。
  2. 除了断言语法之外,MiniTest 还支持期望式的语法,就像 rspec 一样,并且因为是 ruby 集成的,不需要引入外部库 ..... 还有很多吧

第一个小例子

废话不多说,直接来例子吧 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

更多方法参见AssertionsExpectations

下面是大家关心的怎么在 rails 中应用呢 只需要几步就可以了

  1. 在 Gemfile 中加上gem "minitest-rails"
  2. 安装他 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

暂无回复。
需要 登录 后方可回复, 如果你还没有账号请 注册新账号