Include module in all MiniTest tests like in RSpec

前端 未结 3 2045
滥情空心
滥情空心 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 14:54

    One thing I will do is create my own Test class inheriting from Minitest::Test. This allows me to do any sort of configuration on my base test class and keeping it isolated to my own project1.

    # test_helper.rb
    include 'helpers/my_useful_module'
    module MyGem
      class Test < Minitest::Test
        include MyUsefulModule
      end
    end
    
    # my_test.rb
    include 'test_helper'
    module MyGem
      MyTest < Test
      end
    end
    

    1 This is most likely unneeded, but I like keeping all my gem code isolated.

    0 讨论(0)
  • 2021-02-14 14:59

    minitest does not provide a way to include or extend a module into every test class in the same way RSpec does.

    Your best bet is going to be to re-open the test case class (differs, depending on the minitest version you're using) and include whatever modules you want there. You probably want to do this in either your test_helper or in a dedicated file that lets everyone else know you're monkey-patching minitest. Here are some examples:

    For minitest ~> 4 (what you get with the Ruby Standard Library)

    module MiniTest
      class Unit
        class TestCase
          include MyHelpers
        end
      end
    end
    

    For minitest 5+

    module Minitest
      class Test
        include MyHelperz
      end
    end
    

    You can then use the included methods in your test:

    class MyTest < Minitest::Test # or MiniTest::Unit::TestCase
      def test_something
        help1
        # ...snip...
      end
    end
    

    Hope this answers your question!

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题