This code isn't ideal because it mixes testing phases.
It's a good habit to write tests that proceed linearly through four phases:
- Setup (create the data needed for the test)
- Exercise (perform the behavior: call a method, click the interface element, etc.)
- Verify (make sure the behavior was correct)
- 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.