Techioz Blog

Minitest の初期化されていない定数エラー

概要

rake test を使用して Spec 構文で Minitest を実行しようとしていますが、次のエラーが発生します。

/path/to/gem/spec/script_spec.rb:3:in `<top (required)>': uninitialized constant MyGem (NameError)

私のRakefile:

require 'rake/testtask'

Rake::TestTask.new do |t|
  t.test_files = FileList['spec/*_spec.rb']
end

私のファイル構造:

gem/
--lib/
----script.rb
--spec/
----script_spec.rb
--Rakefile

私のscript.rb:

module MyGem
  class OptionParser
    def self.option?(arg)
      arg =~ /^-{1,2}\w+$/
    end
  end
end

script_spec.rb で Minitest::Spec 構文を使用する:

require "minitest/autorun"

describe MyGem::OptionParser do
  describe "option?" do
    it "must be true for option name" do
      OptionParser.option?('--nocolor').assert true
    end
  end
end

どうすれば修正できますか?もしかしてlibフォルダが読み込まれていないのでしょうか? Spec 構文に関連する何かを見逃していますか?

解決策

MyGem::OptionParser がテストにロードされていません。仕様ファイルでこれを要求するか、すべてのテストで必要なすべてのファイルを要求する spec_helper を作成して、仕様で ‘spec_helper’ のみを要求する必要があります。

MyGem::OptionParser がテストにロードされていません。仕様ファイルでこれを要求するか、すべてのテストで必要なすべてのファイルを要求する spec_helper を作成して、仕様で ‘spec_helper’ のみを要求する必要があります。

# spec/spec_helper.rb
require 'minitest/spec'
require 'minitest/autorun'
require 'script'

そして、これを Rakefile に対して実行すると、require_relative ‘../lib/script’ を実行する代わりに、仕様内で上記のような require ‘script’ を実行できるようになります。

require 'rake/testtask'

Rake::TestTask.new do |t|
  t.test_files = FileList['spec/*_spec.rb']
end

最後に、仕様を機能させるには、script_spec ファイルの先頭に require ‘spec_helper’ を追加します。すべての仕様ファイルに対してこれを行う必要があり、仕様でロードする必要があるすべてのファイルの require を spec_helper ファイルに追加する必要があります。

仕様スタイルのテストも行っているため、テストを次のように変更するとよいでしょう。

MyGem::OptionParser.option?('--nocolor').must_equal true

「spec_helper」ファイルに次のようなコードを含めて、lib フォルダー内のすべてのファイルを自動的にロードすることもできます。

Dir["../lib/**/*.rb"].each do |rb_file|
  require rb_file
end

お役に立てれば!