Reputation: 12066
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
Upvotes: 9
Views: 4857
Reputation: 6959
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
Upvotes: 4
Reputation: 27845
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
Upvotes: 2