minitest-hooks

minitest-hooks adds around and before_all/after_all/around_all hooks for Minitest. This allows you do things like run each suite of specs inside a database transaction, running each spec inside its own savepoint inside that transaction, which can significantly speed up testing for specs that share expensive database setup code.

Installation

gem install minitest-hooks

Source Code

Source code is available on GitHub at github.com/jeremyevans/minitest-hooks

Usage

In Specs (Minitest::Spec)

For all specs

require 'minitest/hooks/default'

For some specs

First, you need to require the library.

require 'minitest/hooks'

You can set the default for some specs to be Minitest::HooksSpec:

MiniTest::Spec.register_spec_type(/something/, Minitest::HooksSpec)

Alternatively, you can include Minitest::Hooks in a specific spec class:

describe 'something' do
  include Minitest::Hooks
end

before_all Hooks

To run code before any specs in the suite are executed, pass :all to before:

describe 'something' do
  before(:all) do
    DB[:table].insert(:column=>1)
  end
end

after_all Hooks

To run code after all specs in the suite are executed, pass :all to after:

describe 'something' do
  after(:all) do
    DB[:table].delete
  end
end

around Hooks

To run code around each spec in a suite, call around with a block, and have the block call super:

describe 'something' do
  around do |&block|
    DB.transaction(:rollback=>:always, :savepoint=>true, :auto_savepoint=>true) do
      super(&block)
    end
  end
end

around_all Hooks

To run code around all specs in a suite, call around(:all) with a block, and have the block call super:

describe 'something' do
  around(:all) do |&block|
    DB.transaction(:rollback=>:always) do
      super(&block)
    end
  end
end

In Tests (Minitest::Test)

Create a subclass of Minitest::Test and include Minitest::Hooks, and have your test classes subclass from that subclass:

require 'minitest/hooks'
class MyTest < Minitest::Test
  include Minitest::Hooks
end

class TestSuite1 < MyTest
end

You can just define the before_all, after_all, around, and around_all methods, instead of using the spec DSL. Make sure to call super when overriding the methods.

class TestSuite1 < MyTest
  def before_all
    super
    DB[:table].insert(:column=>1)
  end

  def after_all
    DB[:table].delete
    super
  end

  def around
    DB.transaction(:rollback=>:always, :savepoint=>true, :auto_savepoint=>true) do
      super
    end
  end

  def around_all
    DB.transaction(:rollback=>:always) do
      super
    end
  end
end

License

MIT

Author

Jeremy Evans <[email protected]>