Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 5 test global setup and teardown

I am using the out of the box, vanilla test suite for Rails 5 beta. I am wondering if anyone has figured out how to run a global setup, and tear down.

The reason this is required to I am spinning up a in memory Elasticsearch cluster before any test begins and stop the cluster once the tests are done.

Rspec is not an option.

like image 360
Bill Avatar asked May 09 '16 02:05

Bill


2 Answers

Under Minitest (which is the default testing environment in Rails 4+), to get the "global setup" behavior, simply run anything in your test_helper.rb (outside the tests themselves or any setup methods), i.e. in the file where you load your testing environment from. The test helper is usually required in the tests, so its code is run once before any tests.

For a "global teardown", Minitest provides the Minitest.after_run method. Anything inside its block will be run once after all tests are finished (it uses the program exit hook). Place it e.g. in the test_helper again. For this to work you need to require 'minitest/autorun' at the beginning of the test helper file.

like image 58
Matouš Borák Avatar answered Nov 22 '22 22:11

Matouš Borák


test/test_helper.rb

class ActiveSupport::TestCase
  # Some pre-generated stuff here

  setup do
    do_something
  end

  teardown do
    do_something
  end
end
like image 40
Artur Beljajev Avatar answered Nov 22 '22 22:11

Artur Beljajev