Topic: RSpec start-up fails with array arguments

I can't figure out why such a simple code fails in such a simple test:

require 'rspec_helper'

module Rename
  describe Options do
    describe "#source folder argument" do
      it "sets a source folder" do
        argv = %w{-s some/folder}
        options = Options.new(argv)
        puts "folder: #{options.source_folder}"
        puts "argv[1] => #{argv[1]}"
        options.source_folder.should eq(argv[1])
      end
    end
  end
end

Options class:

require 'optparse'

module Rename
  class Options
    attr_accessor :source_folder
    SOURCE_FOLDER = Dir.pwd
    TARGET_FOLDER = 'target'
    def initialize(argv)
      @source_folder = SOURCE_FOLDER
      run(argv)  
    end
    
    private
    def run(argv)
      OptionParser.new do |opts|
        opts.banner = "Usage: file renaming and copying [ options ]."

        opts.on("-s [SOURCE_FOLDER]", "--source [SOURCE_FOLDER]", String, "Path to the source files folder containing original files to be renamed and copied, (default=#{SOURCE_FOLDER}") do |folder|          
          @source_folder = folder if folder
        end

        opts.on("-", "--help", "Show this message") do
          puts opts
          exit
        end

        begin
          argv = ["-h"]  if argv.empty?
          opts.parse!(argv)
        rescue OptionParser::ParseError => e
          STDERR.puts e.message, "\n", opts
          exit(1)
        end
      end
    end
  end
end

Here is the output:

Rename::Options
  #source folder argument
folder: some/folder
argv[1] => 
    sets a source folder (FAILED - 1)

Failures:

  1) Rename::Options#source folder argument sets a source folder
     Failure/Error: options.source_folder.should eq(argv[1])
       
       expected: nil
            got: "some/folder"
       
       (compared using ==)
     # ./spec/rename/options_spec.rb:11:in `block (3 levels) in <module:Rename>'

Finished in 0.00115 seconds
1 example, 1 failure

WHY I get nil instead of 'some/folder'?

Last edited by Javix (2012-02-14 17:41:38)

Re: RSpec start-up fails with array arguments

What is strange, if I assign the second element of the array to a variable like this:

module PropertyInjector
  describe Options do
    describe "#when export option passed followed by folder name" do
      it "sets up the export folder" do
        argv = %w{-e path/to/some/folder}                
        source = argv[1]
        options = Options.new(argv)        
        options.export_folder.should == source
      end
    end
  end
end

it passes. Strange... I wonder why RSpec does considers it as nil if I pass argv[1] directly to '==' or 'eq' method?

Re: RSpec start-up fails with array arguments

Damned, I found why. The variable 'argv' was passed by reference to the Options class and was modified inside of it by 'parse'  method. That's why after retuning back to the test process, the 'argv' array was nil.

Last edited by Javix (2012-02-16 06:11:04)