RSpec: Expressive Testing

RSpec: Expressive Testing in Ruby: --- On the inspection bench sits a go/no-go gauge: a hardened steel plug ground to two diameters, one at each end.


The Analogy: The QA Bench With Go/No-Go Gauges

On the inspection bench sits a go/no-go gauge: a hardened steel plug ground to two diameters, one at each end. For a hole drilled to a nominal ten millimetres, the "go" end is cut to the low limit and must slide in; the "no-go" end is cut to the high limit and must not. The inspector reads no number and forms no opinion. They try both ends, and the part either passes or it does not.

The bench holds a rack of gauges, one per feature. The inspector works down a checklist: the hole with a plug gauge, the slot with a feeler, the thread with a ring gauge. Each check is independent, so a part can pass the hole and fail the thread, and the checklist records both verdicts side by side. The list of gauges is the drawing's specification made physical -- every dimension that matters has a gauge, and every gauge maps to a dimension that matters.

The virtue of the method is that it needs no judgement. Two inspectors with the same gauge reach the same verdict, so the bench scales to a thousand parts an hour without the answers drifting. And because each gauge has itself been checked against a master block, the verdict is trusted absolutely: a "go" from a calibrated gauge is not an opinion about the part, it is a fact about it.

The bench fails in four ways. A gauge worn past its own tolerance passes bad parts, and because everyone trusts the gauge, nobody catches the drift until the parts reach a customer. A checklist that omits a critical feature lets a defect through a bench that reports "all clear". A gauge used to measure -- reading how far the plug slid in -- invents a precision the go/no-go method never had. And an inspector who, finding the go end will not enter, files the hole until it does has made the part pass the gauge rather than making the part correct. RSpec reproduces all four, and the last two are the ones that quietly rot a test suite.


Syntax or Core Structure

RSpec is a rack of gauges for code. describe names the part on the bench, it names one feature being checked, and expect(...).to is the gauge sliding in. The framework hides the machinery behind a tidy DSL; the runner below makes the machinery visible so nothing is magic.

# minispec.rb -- describe / it / expect, with the wiring shown.

class Spec
  def initialize
    @examples = 0
    @failures = 0
  end

  def describe(subject)
    puts subject
    yield
    puts format("%d examples, %d failures", @examples, @failures)
  end

  def it(behaviour)
    @behaviour = behaviour
    yield
  end

  def expect(actual)
    Check.new(actual, self)
  end

  def record(ok, detail)
    @examples += 1
    if ok
      puts "  ok   #{@behaviour}"
    else
      @failures += 1
      puts "  FAIL #{@behaviour} -- #{detail}"
    end
  end
end

class Check
  def initialize(actual, spec)
    @actual = actual
    @spec = spec
  end

  def to_eq(expected)
    @spec.record(@actual == expected, "expected #{expected}, got #{@actual}")
  end

  def to_be_truthy
    @spec.record(@actual ? true : false, "expected truthy, got #{@actual}")
  end
end

spec = Spec.new
spec.describe("basic expectations") do
  spec.it("adds numbers")    { spec.expect(2 + 2).to_eq(4) }
  spec.it("concatenates")    { spec.expect("hi " + "bob").to_eq("hi bob") }
  spec.it("counts elements") { spec.expect([1, 2, 3].size).to_eq(3) }
  spec.it("finds a member")  { spec.expect([1, 2, 3].include?(2)).to_be_truthy }
end

Output:

basic expectations
  ok   adds numbers
  ok   concatenates
  ok   counts elements
  ok   finds a member
4 examples, 0 failures

Every line of that output came from a gauge sliding in cleanly. describe("basic expectations") printed the subject and then ran the block of examples; each it recorded the behaviour it was about to check; each expect(...).to_eq(...) compared an actual value against an expected one and asked the runner to record a pass or a fail. The summary line counts examples and failures the same way the bench tallies parts and rejects at the end of a shift.

In real RSpec you write describe, it, and expect with no receiver, because the framework evaluates your file inside an example group where those are already in scope. The explicit spec. prefix here is the only difference, and it is worth seeing once: an expectation is an ordinary method call on an ordinary object, comparing two values and recording a boolean. There is no hidden cleverness -- to_eq is == with a nicer failure message.

The failure message is the part beginners skip and regret. When to_eq fails, the runner prints what was expected and what was actually seen, so a red example tells you the two values without your having to add a puts and run again. A matcher that cannot describe its own failure is a gauge with no markings: it tells you the part is wrong but not by how much.


Technical Depth: Which Gauge, And When It Runs

A matcher is a gauge, and choosing the wrong gauge is the commonest way a passing test fails to mean what its author thought. The two questions that matter are: does this matcher check the value or the object, and does the setup it depends on run once or fresh each time.

The Matchers You Reach For, And What They Actually Check

MatcherWhat it assertsThe gauge it isWhen it misleads
eqtwo values are equal by double-equalsthe everyday go gaugealmost never; this is the default
eqlequal value and same typea stricter value gaugewhen you meant eq and a float sneaks past
equalthe very same object in memoryan identity gaugewhen you wanted value equality, not identity
be_truthythe value is not nil and not falsea coarse pass gaugewhen you needed an exact value, not just truthy
be_nilthe value is exactly nila precise absence gaugerarely; it is unambiguous
includea collection contains an elementa membership gaugewhen order or count also mattered
raise_errorthe block raises the named classthe destructive-test gaugewhen you assert the class but not the message

The row that catches people is eq versus equal. The first checks that two values compare equal; the second checks that they are the same object in memory. A test that means "these two amounts are both 50" but reaches for equal will fail on two separate objects that happen to hold 50, and a test that means "this returns the very same cached instance" but reaches for eq will pass on a fresh copy that merely looks the same.

eq Checks Value, equal Checks Identity

a = "50".dup
b = "50".dup

puts "a == b       -> #{a == b}"
puts "a.equal?(b)  -> #{a.equal?(b)}"
puts "a.equal?(a)  -> #{a.equal?(a)}"

x = 49
y = 49.0
puts "49 == 49.0   -> #{x == y}"
puts "49.eql? 49.0 -> #{x.eql?(y)}"

Output:

a == b       -> true
a.equal?(b)  -> false
a.equal?(a)  -> true
49 == 49.0   -> true
49.eql? 49.0 -> false

Two strings built from the same characters are equal in value but are not the same object, which is why == is true while equal? is false. The integer-versus-float pair is the trap that hides in a real suite: 49 == 49.0 is true, so a test written with eq will happily accept a float where the code used to return an integer. If the distinction matters -- and after a refactor that accidentally introduced floating-point division it very much does -- eql is the gauge that catches it, because it checks type as well as value.

before And let: Setup That Runs Fresh Each Time

class BenchLog
  def initialize
    @runs = []
  end

  def run(name)
    setup = []          # a "before" that rebuilds state per example
    setup << "cart"
    setup << name
    @runs << setup.join("+")
  end

  def report
    @runs.each { |r| puts "  #{r}" }
    puts "distinct setups: #{@runs.uniq.size}"
  end
end

log = BenchLog.new
log.run("adds an item")
log.run("removes an item")
log.run("totals the cart")
log.report

Output:

  cart+adds an item
  cart+removes an item
  cart+totals the cart
distinct setups: 3

The point of a before hook, modelled here by rebuilding setup inside every run, is that each example starts from the same clean state. If the three examples shared one mutable cart, the second would inherit whatever the first left behind, and the order the examples ran in would change the result -- a test that passes alone and fails in the suite. Each setup here is rebuilt from scratch, so all three are independent, which is exactly what distinct setups: 3 records. RSpec's let does the same job lazily: it recomputes its value the first time each example touches it and forgets it before the next, so no example can silently depend on another.


Real World Example: Gauging A Tolerance Band

Here is a real subject to test: a Tolerance class that turns a nominal size and a pair of tolerances into an acceptance band, exactly like the go/no-go gauge. The suite below checks its limits, its acceptance at and around the band, and its three-way verdict -- and then, in a second group, points a gauge at a band built from bad inputs so you can see what a failing example looks like and reads like.

# tolerance_spec.rb -- a real subject, a runner, and one honest failure.

class Tolerance
  attr_reader :nominal, :plus, :minus

  def initialize(nominal, plus, minus)
    @nominal = nominal
    @plus = plus
    @minus = minus
  end

  def min
    nominal - minus
  end

  def max
    nominal + plus
  end

  def accepts?(size)
    size >= min && size <= max
  end

  def verdict(size)
    return "small" if size < min
    return "large" if size > max
    "go"
  end
end

class Spec
  attr_reader :examples, :failures

  def initialize
    @examples = 0
    @failures = 0
  end

  def describe(subject)
    puts subject
    yield
  end

  def it(behaviour)
    @behaviour = behaviour
    yield
  end

  def expect(actual)
    Check.new(actual, self)
  end

  def record(ok, detail)
    @examples += 1
    if ok
      puts "  ok   #{@behaviour}"
    else
      @failures += 1
      puts "  FAIL #{@behaviour} -- #{detail}"
    end
  end

  def report
    label = @failures == 1 ? "failure" : "failures"
    puts format("%d examples, %d %s", @examples, @failures, label)
  end
end

class Check
  def initialize(actual, spec)
    @actual = actual
    @spec = spec
  end

  def to_eq(expected)
    @spec.record(@actual == expected, "expected #{expected}, got #{@actual}")
  end

  def to_be_truthy
    @spec.record(@actual ? true : false, "expected truthy, got #{@actual}")
  end
end

spec = Spec.new
t = Tolerance.new(50, 2, 1)

spec.describe("a tolerance band of 50 +2 -1") do
  spec.it("puts min at nominal minus the lower") { spec.expect(t.min).to_eq(49) }
  spec.it("puts max at nominal plus the upper")  { spec.expect(t.max).to_eq(52) }
  spec.it("accepts the nominal size")            { spec.expect(t.accepts?(50)).to_be_truthy }
  spec.it("accepts the low limit")               { spec.expect(t.accepts?(49)).to_be_truthy }
  spec.it("accepts the high limit")              { spec.expect(t.accepts?(52)).to_be_truthy }
  spec.it("rejects a size below the band")       { spec.expect(t.accepts?(48)).to_eq(false) }
  spec.it("rejects a size above the band")       { spec.expect(t.accepts?(53)).to_eq(false) }
  spec.it("calls an in-band size go")            { spec.expect(t.verdict(50)).to_eq("go") }
  spec.it("calls a small size small")            { spec.expect(t.verdict(48)).to_eq("small") }
  spec.it("calls a large size large")            { spec.expect(t.verdict(53)).to_eq("large") }
end

bad = Tolerance.new(50, -2, -1)

spec.describe("an inverted band from negative tolerances") do
  spec.it("should still accept its own nominal") { spec.expect(bad.accepts?(50)).to_be_truthy }
end

spec.report

Output:

a tolerance band of 50 +2 -1
  ok   puts min at nominal minus the lower
  ok   puts max at nominal plus the upper
  ok   accepts the nominal size
  ok   accepts the low limit
  ok   accepts the high limit
  ok   rejects a size below the band
  ok   rejects a size above the band
  ok   calls an in-band size go
  ok   calls a small size small
  ok   calls a large size large
an inverted band from negative tolerances
  FAIL should still accept its own nominal -- expected truthy, got false
11 examples, 1 failure

Ten green, one red, and the red one is worth more than the ten. The band of 50 with tolerances of plus two and minus one has its minimum at 49 and its maximum at 52, so every example in the first group is a gauge sliding cleanly: the nominal and both limits are accepted, a size below and a size above are rejected, and the three-way verdict names a small size small, a large size large, and an in-band size go.

The eleventh example points a gauge at a band built from negative tolerances, and the failure message does the work a raw false never could. expected truthy, got false tells you immediately that accepts?(50) came back false, which is impossible for an honest band centred on 50 -- so the fault is not in the test, it is in the band. That is the difference between a matcher with a failure message and a bare assertion: the red line points at the defect instead of merely announcing one.

The failing example is deterministic, which is what makes it useful in a lesson. Tolerance.new(50, -2, -1) puts the minimum at 51 and the maximum at 48, so the band is inverted and accepts? returns false for every possible size, including its own nominal. The example fails the same way on every run, on every machine, because nothing in it depends on time, ordering, or randomness. Note too that had the eleventh example instead raised an exception, this runner would have died before report ran and printed no summary at all -- so a green summary here means "nothing raised" as much as it means "nothing failed".

The design flaw is in Tolerance itself, and the failing test is what exposes it: initialize never checks that plus and minus are non-negative, so it silently accepts -2 and -1 and builds a band whose minimum sits above its maximum. A validating constructor would raise an ArgumentError at construction, turning a mysterious "accepts nothing" bug into an immediate, located failure. Three narrower faults sit alongside it: the runner rescues nothing, so one raised exception ends the whole suite and the summary line is trustworthy only when every example returned normally; to_eq compares with double-equals, so to_eq(49) would pass against 49.0 and a type regression would slip straight through, exactly the trap the Technical Depth section gauged; and because it stores the behaviour in one shared field and record increments the example count on every expectation, two expectations inside one it are counted as two examples with the same name, so the example count measures assertions rather than behaviours.


Common Mistakes

  1. Writing a test that cannot fail. An example with no expectation, or one whose expectation is a tautology like expect(true).to_be_truthy, is a worn gauge: it is green on every run and tells you nothing. The only way to trust a green test is to have seen it red first, so break the code deliberately once and confirm the test catches it.
  1. Reaching for equal when you mean eq. equal checks object identity, not value, so it fails on two distinct objects that hold the same value. Unless you are specifically asserting that a method returns the very same cached instance, eq is the gauge you want.
  1. Testing with be_truthy when the value matters. be_truthy passes for true, for 5, for "no", and for any object that is not nil or false. If the method is supposed to return exactly true or exactly a count, assert that value; a coarse gauge hides a return type that quietly changed.
  1. Letting examples share mutable state. An example that mutates an object built once at the top of the file leaves that mutation for the next example. The suite then passes or fails depending on the order it runs in, and a single-example run disagrees with the full suite. Build fresh state per example with before or let.
  1. Asserting on the whole object when one field matters. Comparing an entire record against a fixed expected object makes every unrelated field a reason to fail, so a harmless new attribute turns dozens of specs red. Assert the field the behaviour is about, and let the rest change freely.
  1. Over-mocking until the test tests the mock. Replacing every collaborator with a stub that returns exactly what the test expects produces a green suite that proves only that your stubs match your assumptions. When the real collaborator changes, the code breaks and the tests stay green. Mock at the edges -- the network, the clock -- not the object under test.
  1. Coupling a spec to an incidental message. raise_error(ArgumentError, "bad size") fails the day someone improves the wording to "size must be positive", even though the behaviour is unchanged. Assert the error class, and match the message only with a fragment or pattern if the exact text is genuinely part of the contract.
  1. Depending on time, order, or randomness. A spec that reads the current time, relies on hash-iteration order, or seeds nothing before calling rand is a gauge that gives a different verdict on Tuesday. Freeze the clock, sort before comparing, and seed the generator, so the same input always produces the same verdict.
  1. Chasing a green bar by weakening the test. When a gauge will not pass, filing the part is the wrong fix; loosening the expectation until it goes green is the same error in code. A failing test is information about the code, and the response is to fix the code or, if the expectation was genuinely wrong, to change it deliberately and say why -- not to sand it down until it stops complaining.

Best Practices

  • See every test fail before you trust it green. Break the code, watch the red line, restore the code. A test you have never seen fail is a gauge you have never calibrated.
  • Name the example by the behaviour, not the method. "rejects a size below the band" tells a future reader what broke when it goes red; "test accepts?" tells them only where to start looking.
  • Choose the narrowest matcher that states the intent. eq for value, eql when type matters, be_nil for exact absence, raise_error with a class for failure paths. The matcher is documentation of what the behaviour actually is.
  • Build fresh state for each example. Use before or let so no example inherits another's mutations, and the suite gives the same verdict regardless of the order it runs in.
  • Assert on what the behaviour changes, not on everything around it. A focused expectation survives unrelated additions to the object and fails only when the thing it describes actually breaks.
  • Keep failure messages informative. A matcher should say what it expected and what it saw, so a red example is a diagnosis rather than a prompt to add print statements and run again.
  • Make every spec deterministic. Freeze time, seed randomness, and sort unordered collections before comparing, so a failure means a real defect and not the calendar.
  • Test behaviour through the public interface. Specs that reach into private methods break on every refactor that keeps the behaviour intact, which trains the team to distrust the suite.

Practice Exercises

  1. Fix the subject the failing test found. Add validation to Tolerance#initialize so it raises an ArgumentError when plus or minus is negative, then replace the failing example with one that expects the construction to raise, and show the suite is green again with the bug now caught at construction time.
  1. Add the missing matcher. Extend the Check class with a to_raise matcher that runs a block, catches any exception, and records a pass if the raised class matches the one expected. Use it to test that the validated Tolerance raises on bad input, and show the pass line in the output.
  1. Catch the type regression. Add a to_eql matcher that checks value and type with eql?, then write two examples against a value of 49: one with to_eq and one with to_eql, each fed 49.0, and show that the first passes while the second fails -- demonstrating the gauge that catches an integer silently becoming a float.
  1. Prove the order-independence. Add a second subject with mutable state, write three examples that each mutate it, and show that rebuilding the subject before each example gives ten-out-of-ten green while sharing one instance makes at least one example's verdict depend on the order the examples ran in.