describe
and context
group related checks and set the structure of the test.
Structure is the skeleton of the test, reflecting its logic. Without structure, the test is difficult to read: the narrative jumps around, attention wanders, and searching for related checks is frustrating.
Without structure:
it "#accessible_projects return all system projects when user is admin"
it "returns no projects when user is not admin"
it "returns user full name with email"
With structure:
describe "#accessible_projects" do
context "when user is admin" do
it "returns all system projects"
context "when user is NOT admin" do
it "returns no projects"
describe "#user_name_with_email" do
it "returns user full name with email in parens"
When and what to use
I use describe
for entities (who?, what?) and context
for states (when?, if?, with what conditions?). It makes it easier to navigate possible situations and explore conditions.
# Meh
context "associations"
context "#full_name"
describe "when user is admin"
describe "with valid params"
# Good
describe "associations"
describe "#full_name"
context "when user is admin"
context "with invalid params"
I start contexts with words when, if, with, given. If I see them in the test description, I pull them out:
# Bad: condition, situation description
# (user is editor) is hard to notice
it "returns only published posts when user is not editor"
it "returns published and draft posts when user is editor"
# Good: the situation is explicitly stated in the context
context "when user is editor" do
it "returns published and draft posts"
context "when user is NOT editor" do
it "returns only published posts"
Cheat sheet
describe <something>
context <when... / if... / with... / given...>
Top comments (0)