Both before
and after
accept an argument, which can be :suite
, :context
, or :example
. The default value is :example
, so when we defined the before
block in our tests above, we were actually defining a before(:example)
block. Similarly, our after
block was actually an after(:example)
block. This means that the block is executed before (or after) each test case in the context where it is defined. This is most often the desired behavior for hooks. However, there are cases when setup and teardown are not required after each test. Usually, to improve performance, in those cases you can set the hook to run before the context where it is defined, or before the entire test suite.
There is also an around
block (which also accepts an argument of :suite
, :context
, or :example
) that can be used to define a single block that does both setup and teardown. I prefer to usually keep setup and teardown separate. Also, around
hooks do not have access to the test context like...