Pregunta

After including a module in spec_helper, I am running Minitest spec for a class inside that module and get this error:

test_0001_must be true for option name(MyGem::OptionParser::option?):
NoMethodError: undefined method `option?' for OptionParser:Class

I'm testing lib/options/options.rb:

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

With spec/options_spec.rb:

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

Running the test with MyGem::OptionParser instead of just OptionParser doesn't cause errors. But similar test on lib/script.rb runs without errors without MyGem:: prefix.

My file structure:

gem/
|-lib/
| |-options/
| | |-options.rb
| |-script.rb
|-spec/
| |-script_spec.rb
| |-options_spec.rb
| |-spec_helper.rb
|-Rakefile

I include MyGem in spec_helper. What have I got wrong?

¿Fue útil?

Solución

Minitest either already includes or auto loads Ruby's own OptionParser, so that presumably is taking precedence and preventing the loading of your version. Here's evidence:

MacbookAir1:so1 palfvin$ irb
2.0.0p247 :001 > OptionParser
NameError: uninitialized constant OptionParser
    from (irb):1
    from /Users/palfvin/.rvm/rubies/ruby-2.0.0-p247/bin/irb:16:in `<main>'
2.0.0p247 :002 > require 'minitest'
 => true 
2.0.0p247 :003 > OptionParser
 => OptionParser 
2.0.0p247 :004 > 

Otros consejos

If you have exactly the same MyGem::OptionParser defined in your script.rb file, that is likely what is causing issues in your spec. Try using another namespace for your code in options.rb like so:

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

Then make sure to include it in your spec_helper or in your options_spec file.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top