9

I would like to have a method that runs once per file rather than once per test. I've seen some references to a "before" method, but doesnt appear to work with MiniTest. Ideally, something like this:

class MyTest < ActiveSupport::TestCase
   before do
      # Executes once per file
   end

   setup do
      # Executes once per test
   end

   # Tests go here
end
Tom Rossi
  • 11,604
  • 5
  • 65
  • 96
  • It would be nice to have a `teardown` solution as well for a *once for a test file* situation. – mlt Aug 15 '17 at 22:12

2 Answers2

4

Before is used when you are using spec dsl for minitest, it is equivalent to setup. You can use setup, if you use setup in your test_helper.rb file it 'll be executed once before all tests.

setup can also be declared in test classes. Use setup, place a flag and update the flag on first time.

x = 0
setup do
  if x == 0
    x = x + 1
    puts "Incremented in x = #{x}"
  end
end

OR

setup_executed = false
setup do
  unless setup_executed
    #code goes here
    setup_executed = true
  end
end
Malik Shahzad
  • 6,703
  • 3
  • 37
  • 49
  • 3
    `setup` method inside ActiveSupport::TestCase class is executed before each test method/call again. Not once per class. – Foton Feb 14 '17 at 16:24
  • @Foton is right, setup is not the correct answer for this question. – msdundar Apr 29 '18 at 23:10
1

You can add your code outside the class definition.

  # Executes once per file
  puts "Executed once"

  class MyTest < ActiveSupport::TestCase

     setup do
        # Executes once per test
     end

     # Tests go here
  end

You can also add your code inside the class definition, but outside of any method:

  class MyTest #< ActiveSupport::TestCase
    # Executes once per Testclass
     puts "Executed once"

     setup do
        # Executes once per test
     end

     # Tests go here
  end
knut
  • 27,320
  • 6
  • 84
  • 112
  • Also, in order for database records to persist from one test to another, you'll probably need to disable "transaction fixtures" (wrapping all database operations in a transaction that gets rolled back after the test case) for the test file where you want to do this. – Nick Davies Sep 18 '17 at 15:35