Ruby Minitest:套件级或类级设置? [英] Ruby Minitest: Suite- or Class- level setup?

查看:63
本文介绍了Ruby Minitest:套件级或类级设置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用内置的Ruby Minitest框架,是否有办法在整个套件运行之前甚至在整个TestClass运行之前运行一些代码?我在这个问题的答案中看到了Test :: Unit: :after_tests可用于在运行所有测试之后运行代码;在所有测试运行之前,有没有类似的方法可以运行代码?

Using the built-in Ruby Minitest framework, is there a way to run some code once before the entire suite runs, or even once before an entire TestClass runs? I see in the answer to this question that Test::Unit::after_tests can be used to run code after all tests have been run; is there a similar method to run code before all tests have run?

我想使用此功能在测试运行之前初始化测试数据库,并在测试全部运行后将其拆除.

I would like to use this functionality to initialize a test database before the tests run and tear it down after they have all run.

谢谢!

推荐答案

这是从MiniTest 文档修改而来的(在可自定义的测试运行器类型"下).

This is modified from the MiniTest docs (under Customizable Test Runner Types).

class Burger
  def initialize
    puts "YOU CREATED A BURGER"
  end

  def has_cheese?
    true
  end

  def has_pickle?
    false
  end
end

gem 'minitest'

require 'minitest/unit'
MiniTest::Unit.autorun

class MyMiniTest
  class Unit < MiniTest::Unit

    def before_suites
      # code to run before the first test
      p "Before everything"
    end

    def after_suites
      # code to run after the last test
      p "After everything"
    end

    def _run_suites(suites, type)
      begin
        before_suites
        super(suites, type)
      ensure
        after_suites
      end
    end

    def _run_suite(suite, type)
      begin
        suite.before_suite if suite.respond_to?(:before_suite)
        super(suite, type)
      ensure
        suite.after_suite if suite.respond_to?(:after_suite)
      end
    end

  end
end

MiniTest::Unit.runner = MyMiniTest::Unit.new

class BurgerTest < MiniTest::Unit::TestCase

  def self.before_suite
    p "hi"
  end

  def self.after_suite
    p "bye"
  end

  def setup
    @burger = Burger.new
  end

  def test_has_cheese
    assert_equal true, @burger.has_cheese?
  end

  def test_has_pickle
    assert_equal false, @burger.has_pickle?
  end

end

请注意,您包含了gem 'minitest'来使用gem而不是没有MiniTest::Unit.runner方法的捆绑版本.这是输出.

Note that you I included gem 'minitest' to use the gem instead of the bundled version which didn't have the MiniTest::Unit.runner method. Here's the output.

Run options: --seed 49053

# Running tests:

"Before everything"
"hi"
YOU CREATED A BURGER
.YOU CREATED A BURGER
."bye"
"After everything"


Finished tests in 0.000662s, 3021.1480 tests/s, 3021.1480 assertions/s.

2 tests, 2 assertions, 0 failures, 0 errors, 0 skips

因此,它两次调用#setup,但是只调用一次.before_suite.after_suite,这就是我想要的.

So it calls #setup twice, but .before_suite and .after_suite only once, which is what you are looking for I think.

这篇关于Ruby Minitest:套件级或类级设置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆