DEV Community

Vasily Polovnyov
Vasily Polovnyov

Posted on

4 1

Explaining RSpec describe, context in 2 minutes

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"
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

Cheat sheet

describe <something>
context <when... / if... / with... / given...>
Enter fullscreen mode Exit fullscreen mode

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free β†’