Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include module in all MiniTest tests like in RSpec

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

module MyHelpers
  def help1
    puts "hi"
  end
end

and include it in every spec like this:

RSpec.configure do |config|
  config.include(MyHelpers)
end

and use it in my tests like this:

describe User do
  it "does something" do
    help1
  end
end

How can I include a module into all MiniTest tests without repeating myself in every test?

like image 492
BvuRVKyUVlViVIc7 Avatar asked Nov 07 '13 16:11

BvuRVKyUVlViVIc7


1 Answers

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!

like image 172
Paul Simpson Avatar answered Sep 29 '22 00:09

Paul Simpson