在RSpec中的所有MiniTest测试中包含模块
在RSpec中,我可以在/spec/support/...
创建辅助模块/spec/support/...
module MyHelpers def help1 puts "hi" end end
并将其包含在每个规范中:
RSpec.configure do |config| config.include(MyHelpers) end
并在我的测试中使用它,如下所示:
describe User do it "does something" do help1 end end
如何在所有MiniTest测试中包含一个模块,而不必在每次测试中重复自己?
minitest没有像RSpec那样提供 extend
模块include
或extend
到每个测试类的方法。
您最好的选择是重新打开测试用例类(根据您使用的最小版本而有所不同)并include
您想要的任何模块。 您可能希望在test_helper
或专用文件中执行此操作,该文件可让其他人知道您是最小的猴子修补程序。 这里有些例子:
对于minitest~> 4(你使用Ruby标准库得到的)
module MiniTest class Unit class TestCase include MyHelpers end end end
最小的5+
module Minitest class Test include MyHelperz end end
然后,您可以在测试中使用包含的方法:
class MyTest < Minitest::Test # or MiniTest::Unit::TestCase def test_something help1 # ...snip... end end
希望这能回答你的问题!
从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
只需在文件中定义模块并使用require将其拉入。例如,如果在test / support / useful_stuff.rb中定义了’UsefulStuff’,则可能在您的单个测试文件中需要’support / useful_stuff’。
更新:
为了澄清,在您现有的test / test_helper.rb文件或您创建的新test / test_helper.rb文件中,包含以下内容:
Dir[Rails.root.join("test/support/**/*.rb")].each { |f| require f }
这将需要test / support子目录中的所有文件。
然后,在每个单独的测试文件中添加
require 'test_helper'
这与RSpec完全类似,在每个spec文件的顶部都有一个require’pect_helper’行。
我要做的一件事是创建我自己的inheritance自Minitest::Test
的Test
类。 这允许我在我的基础测试类上进行任何类型的配置,并使其与我自己的项目隔离1 。
# 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这很可能是不必要的,但我喜欢保留所有gem代码。