RSpec Describe and Context

RSpec’s describe and context methods are both aliased to the same behavior, hence functionally identical. However, practice has evolved a clear distinction in use, each best used for specific purposes:

  • describe is used for declaring which method is being tested. The convention for the description string is to use the method name, prefixing instance methods with #, and class methods with ..

  • context is used for declaring the state of the object being tested. Multiple context blocks are nested in the relevant describe blocks.

When used appropriately, describe and context can help with designing classes (Test-Driven Design - TDD). The control of flow through methods in a class becomes visible as the describe and context blocks are defined in the tests. This may expose errors in logic. Test coverage tools provide even more insight.