Four-Phase Test

The Four-Phase Test is a testing pattern, applicable to all programming languages and unit tests (not so much integration tests).

It takes the following general form:

test do
  setup
  exercise
  verify
  teardown
end

There are four distinct phases of the test. They are executed sequentially.

setup

During setup, the system under test (usually a class, object, or method) is set up.

user = User.new(password: 'password')

exercise

During exercise, the system under test is executed.

user.save

verify

During verification, the result of the exercise is verified against the developer’s expectations.

user.encrypted_password.should_not be_nil

teardown

During teardown, the system under test is reset to its pre-setup state.

This is usually handled implicitly by the language (releasing memory) or test framework (running inside a database transaction).

all together

The four phases are wrapped into a named test to be referenced individually.

Our style guide advises we “Separate setup, exercise, verification, and teardown phases with newlines.”

it 'encrypts the password' do
  user = User.new(password: 'password')

  user.save

  user.encrypted_password.should_not be_nil
end

Go forth and test in phases.

Pair with one of our expert developers to level up your skills with Coaching by thoughtbot. Save time learning best practices and techniques for reducing technical debt in Ember, Ruby, Haskell, and Go in 1-on-1 sessions tailored to your goals.