Include module in all MiniTest tests like in RSpec

前端 未结 3 2032
滥情空心
滥情空心 2021-02-14 14:08

In RSpec I could create helper modules in /spec/support/...

module MyHelpers
  def help1
    puts \"hi\"
  end
end

and include it

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-14 15:00

    From the Minitest README:

    === How to share code across test classes?
    
    Use a module. That's exactly what they're for:
    
    module UsefulStuff
      def useful_method
        # ...
      end
    end
    
    describe Blah do
      include UsefulStuff
    
      def test_whatever
        # useful_method available here
      end
    end
    

    Just define the module in a file and use require to pull it in. For example, if 'UsefulStuff' is defined in test/support/useful_stuff.rb, you might have require 'support/useful_stuff' in either your individual test file.

    UPDATE:

    To clarify, in your existing test/test_helper.rb file or in a new test/test_helper.rb file you create, include the following:

    Dir[Rails.root.join("test/support/**/*.rb")].each { |f| require f }
    

    which will require all files in the test/support subdirectory.

    Then, in each of your individual test files just add

    require 'test_helper'
    

    This is exactly analogous to RSpec, where you have a require 'spec_helper' line at the top of each spec file.

提交回复
热议问题