'How to run code before each test case in all tests in MiniTest?

I need to run code before each test in all my tests in MiniTest.

Before I did:

MiniTest::Unit::TestCase.add_setup_hook do
   ...code to run before each test
end

After I upgraded MiniTest to version 4.7.2 it shows the following error:

undefined method `add_setup_hook' for MiniTest::Unit::TestCase:Class (NoMethodError)

I am using Ruby MRI 2.0.0p0.

SOLUTION

module MyMinitestPlugin
  def before_setup
    super
    # ...code to run before all test cases
  end

  def after_teardown
    # ... code to run after all test cases
    super
  end
end

class MiniTest::Unit::TestCase
  include MyMinitestPlugin
end


Solution 1:[1]

I think that you're looking for the setup() method.

Solution 2:[2]

Update 2019

Don't write a plugin for this, plugins are intended for gems which extend Minitest functionality, not for test authors.

If you write Minitest Specs, you can do the following instead:

class Minitest::Spec
  before :each do
    [do stuff]
  end
end

Solution 3:[3]

If using MiniTest, you can set that in test/test_helper.rb:

class ActiveSupport::TestCase
...
    setup do
         ...code to run before each test
    end
end

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 the Tin Man
Solution 2 svoop
Solution 3 akira