gpt4 book ai didi

ruby-on-rails - 在所有 MiniTest 测试中包含模块,就像在 RSpec 中一样

转载 作者:数据小太阳 更新时间:2023-10-29 06:45:23 24 4
gpt4 key购买 nike

在 RSpec 中,我可以在 /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 自述文件:

=== 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 }

这将需要测试/支持子目录中的所有文件。

然后,在您的每个单独的测试文件中添加

require 'test_helper'

这与 RSpec 非常相似,您在每个规范文件的顶部都有一个 require 'spec_helper' 行。

关于ruby-on-rails - 在所有 MiniTest 测试中包含模块,就像在 RSpec 中一样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19841510/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com