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:
-
describeis 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.. -
contextis used for declaring the state of the object being tested. Multiplecontextblocks are nested in the relevantdescribeblocks.
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.
Links
- Rubocop is configured to warn by default as recommended by the RSpec style guide.
- Here is a great two minute explanation