liveBook · Manning

Test setup

As explained in The Well-Grounded Rubyist, Fourth Edition

A setup method is a test-support method that prepares the state required before a test method runs.

A setup method prepares shared state before each test method runs. In MiniTest, the method name setup is recognized automatically, so every test receives an independently initialized fixture. section 15.5.1

A fresh deck for every test

A CardTest setup method assigns a new PlayingCards::Deck to @deck. test_deal_one can remove one card and expect 51 remaining; test_deal_many can remove five and expect 47, without either test inheriting the other’s mutations. section 15.5.1

The same pattern can be implemented with callbacks: MicroTest observes subclass method definitions, creates an instance for methods beginning with test, runs setup when present, and then invokes the test. section 15.5.2

A setup method supports a predictable test lifecycle:

  • Construct the fixture before each test method. section 15.5.1
  • Keep tests independent by preventing state changes from carrying between runs. section 15.5.1
  • Leave setup optional when a test needs no shared preparation. section 15.5.2

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains MiniTest convention and demonstrates callback-based execution, stopping short of broader fixture lifecycle behavior.
Examples
Uses a PlayingCards::Deck fixture, one-card and five-card dealing tests, and a MicroTest implementation.
What it assumes
Assumes Ruby classes, instance variables, test methods, assertions, and basic inheritance.
What you can do after
Apply it via MiniTest by defining setup to initialize state before each test method.
How it connects
Connects setup with test methods, test independence, assertions, inheritance, and method_added callbacks.

Also explained in

Compare how 2 books explain test setup →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.