Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you write a setup method that is executed just once for a test file?

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
like image 680
Tom Rossi Avatar asked Oct 22 '15 20:10

Tom Rossi


1 Answers

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
like image 80
Malik Shahzad Avatar answered Nov 15 '22 05:11

Malik Shahzad