4. The Test Case Life Cycle

You already saw a simple test case in action. It looked something like this:

require 'test/unit'

class MyTestCase < Test::Unit::TestCase

  def test_1
    assert true
  end

  def test_2
  end

  def test_3
  end

end

You saw that:

  • we need to use require ‘test/unit’
  • we need to inherit from Test::Unit::TestCase
  • we need to define methods that start with test
  • we need assertions to prove our code works

Next, we’re going to look at the flow of how test cases are run.

When a test case is run, the testing framework creates a ‘fresh’ object before running each test. That allows the test to not have to worry about what state the other test methods leave the object in. So for the above example, the testing flow looks like this when run:

  • an object of class MyTestCase is created
  • method test_1 is run
  • the test case object is destroyed

then…

  • a brand new object of class MyTestCase is created
  • method test_2 is run
  • the test case object is destroyed

then…

  • one last object of class MyTestCase is created
  • method test_3 is run
  • the test case object is destroyed

Now, there are 2 special methods that you can use to hook into this process. One is called setup and the other is called teardown.

Let’s rewrite our test.

require 'test/unit'

class MyTestCase < Test::Unit::TestCase

  # called before every single test
  def setup
    @name = 'jimmy'
    @age = 150
  end

  # called after every single test
  def teardown
  end

  # our tests
  def test_1
    assert true
  end

  def test_2
  end

  def test_3
  end

end

The setup method will always be called just before the test method. Comparatively, the teardown method will always be called always be called just after the test method. So now, the flow looks like this:

  • an object of class MyTestCase is created
  • method setup is run
  • method test_1 is run
  • method teardown is run
  • the test case object is destroyed

then…

  • a brand new object of class MyTestCase is created
  • method setup is run
  • method test_2 is run
  • method teardown is run
  • the test case object is destroyed

then…

  • one last object of class MyTestCase is created
  • method setup is run
  • method test_3 is run
  • method teardown is run
  • the test case object is destroyed

What can you do with this? Well, the setup method is good for stuff like creating objects that each method uses. For example, maybe we need to create a user and populate her with sample data before running each of the tests?

As you’ll see later, Rails uses the setup and teardown methods extensively.