Ruby on rails 如何编写针对测试文件只执行一次的设置方法?

Ruby on rails 如何编写针对测试文件只执行一次的设置方法?,ruby-on-rails,ruby,minitest,Ruby On Rails,Ruby,Minitest,我希望有一个方法,每个文件运行一次,而不是每个测试运行一次。我见过一些对“before”方法的引用,但似乎不适用于MiniTest。理想情况下,类似这样的情况: class MyTest < ActiveSupport::TestCase before do # Executes once per file end setup do # Executes once per test end # Tests go here end

我希望有一个方法,每个文件运行一次,而不是每个测试运行一次。我见过一些对“before”方法的引用,但似乎不适用于MiniTest。理想情况下,类似这样的情况:

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

   setup do
      # Executes once per test
   end

   # Tests go here
end
classmytest
您可以在类定义之外添加代码

  # Executes once per file
  puts "Executed once"

  class MyTest < ActiveSupport::TestCase

     setup do
        # Executes once per test
     end

     # Tests go here
  end
#每个文件执行一次
将“执行一次”
类MyTest
您还可以在类定义内部,但在任何方法外部添加代码:

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

     setup do
        # Executes once per test
     end

     # Tests go here
  end
class MyTest#
在您使用spec dsl进行minitest时使用之前,它相当于设置。 您可以使用设置,如果在test\u helper.rb文件中使用设置,它将在所有测试之前执行一次

安装程序也可以在测试类中声明。使用设置,放置标志并在第一次更新标志

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


setup
ActiveSupport中的方法::TestCase类在每次测试方法/调用之前执行。不是每个类一次。@福田是对的,安装程序不是这个问题的正确答案。最好有一个
teardown
解决方案,以及一个测试文件一次的解决方案。另外,为了让数据库记录从一个测试持续到另一个测试,您可能需要禁用“事务固定装置”(将所有数据库操作包装在测试用例后回滚的事务中)用于要执行此操作的测试文件。
setup_executed = false
setup do
  unless setup_executed
    #code goes here
    setup_executed = true
  end
end