Test Smells

Flashcard 2 of 5

The following pseudocode shows up in a PR, what change might you (nicely) suggest?

feature do
  scenario do
    setup_some_things

    promote_user_to_admin
    attempt_to_visit_admin_dashboard

    expect_to_be_on_admin_dashboard

    attempt_to_perform_privileged_operation

    expect_operation_to_have_succeeded
  end
end

This code isn't ideal because it mixes testing phases.

It's a good habit to write tests that proceed linearly through four phases:

  1. Setup (create the data needed for the test)
  2. Exercise (perform the behavior: call a method, click the interface element, etc.)
  3. Verify (make sure the behavior was correct)
  4. Teardown (clean up after yourself, often handled by the testing framework)

Good tests follow these phases in order and do not revisit (or mix) phases. Following this pattern gives your tests a predictability that will make them more readable (and who hates that?).

Here's our code from before, but annotated with the applicable phases:

feature do
  scenario do
    # Setup
    setup_some_things

    # Exercise
    promote_user_to_admin
    attempt_to_visit_admin_dashboard

    # Verify
    expect_to_be_on_admin_dashboard

    # Exercise (again)
    attempt_to_perform_privileged_operation

    # Verify (again)
    expect_operation_to_have_succeeded
  end
end

Notice the bits labeled "(again)." It's a good idea to avoid that.

If you find yourself tempted to jam a second pair of Exercise and Verify phases into a test, you should probably extract the Setup and create a second test case.

What's that? You want to watch a video dedicated to this topic? Then you'll love this Weekly Iteration episode.

Return to Flashcard Results