Escaping your test suite with your life

Arnold in Running Man

One testing feature that I really miss in test/unit, is rspec's before(:all) blocks. These are similar to your test/unit setup methods, yet they only run once for the whole test suite.

I was able to implement before(:all) callbacks in context, but the code for that is a little gnarly. Basically, I had to hack the Test::Unit::TestSuite#run method to run some callbacks before and after the test run. Downside: it doesn't work in minitest (it could, but the code isn't very inviting).

So, what if I could do something like this?

class MyTest < ActiveSupport::TestCase
  block = RunningMan::Block.new do
    # something expensive
  end

  setup { block.run(self) }
end

Running Man gives you before(:all) callbacks in test/unit and minitest (ruby 1.9). Basically, you create a RunningMan::Block and call #run in a normal setup call in your tests. The RunningMan::Block calls the block just once, and fills your test case instances with the right instance variables on each test. No muss, no ugly test/unit hacking. (Ok, before you call me a liar, that hack was to allow special teardown blocks on the last test. That feature doesn't work in ruby 1.9, unfortunately.)

This was extracted from GitHub and rewritten when I wanted to use it in a small, non-Rails project.

class MyTest < ActiveSupport::TestCase
  fixtures do
    @post = Post.make # <3 Machinist
  end

  test "check something on post" do
    assert_equal 'foo', @post.title
  end

  test "delete post" do
    @post.destroy
  end
end