Is there an alternative to RSpec's before(:suite)
and after(:suite)
in MiniTest?
I suspect that a custom test runner is in order, however I cannot imagine it is not a common requirement, so somebody has probably implemented in. :-)
Is there an alternative to RSpec's before(:suite)
and after(:suite)
in MiniTest?
I suspect that a custom test runner is in order, however I cannot imagine it is not a common requirement, so somebody has probably implemented in. :-)
To run code before each test, use
before
. You're operating here in the context of an instance, possibly of a class generated implicitly bydescribe
, so instance variables set inbefore
are accessible in each test (e.g. inside anit
block).To run code before all tests, simply wrap the tests in a class, a subclass of
MiniTest::Spec
or whatever; now, before the tests themselves, you can create a class or module, set class variables, call a class method, etc., and all of that will be available in all tests.Example:
Here's the output, along with my comments in braces explaining what each line of the output proves:
(Note that I do not mean this output to imply any guarantee about the order in which tests will run.)
Another approach is to use the existing
before
but wrap code to run only once in a class variable flag. Example:There are
setup()
andteardown()
methods available. The documentation also listsbefore()
andafter()
as being available.Edit: Are you looking to run something before each test or before or after the whole suite is finished?
You can also add an after test callback by updating your test_helper.rb (or spec_helper.rb) like this
One simple way to do this is to write a guarded class method, and then call that in a
begin
.A Minitest::Spec example:
...to get
As noted above in Caley's answer and comments,
MiniTest::Unit
contains the functionafter_tests
. There is nobefore_tests
or equivalent, but any code in yourminitest_helper.rb
file should be run before the test suite, so that will do the office of such a function.Caveat: Still relatively new at Ruby, and very new at Minitest, so if I'm wrong, please correct me! :-)
To get this to work with the current version of Minitest (5.0.6) you need to
require 'minitest'
and useMinitest.after_run { ... }
.https://github.com/seattlerb/minitest/blob/master/lib/minitest.rb https://github.com/seattlerb/minitest/blob/master/lib/minitest/unit.rb