How to test a script that generates files

I am creating Rubygem which will allow me to generate jekyll post files. One of the reasons I am developing this project is to study TDD. This pearl is strictly functional on the command line, and it must do a series of checks to make sure it finds the directory _posts. It depends on two things:

  • Wether option passed or not location
    • Is this location setting valid?
  • Location parameter was not passed
    • Is the dir directory in the current directory?
    • Are dir messages the current working directory?

At this point, it's really hard for me to test this part of the application. Therefore, I have two questions:

  • Is it acceptable / normal to skip tests for small parts of the application as described above?
  • If not, how can you test file manipulation in ruby ​​with minitest?
+3
source share
2 answers

Some projects I've seen implement their command line tools as Command objects (for example: Rubygems and my escape stone). ARGV, , . . , , , STDOUT/STDIN. , , / . , , , . Command.

:

require 'pathname'

class MyCommand
  attr_accessor :input, :output, :error, :working_dir

  def initialize(options = {})
    @input = options[:input] ? options[:input] : STDIN
    @output = options[:output] ? options[:output] : STDOUT
    @error = options[:error] ? options[:error] : STDERR
    @working_dir = options[:working_dir] ? Pathname.new(options[:working_dir]) : Pathname.pwd
  end

  # Override the puts method to use the specified output stream
  def puts(output = nil)
    @output.puts(output)
  end

  def execute(arguments = ARGV)
    # Change to the given working directory
    Dir.chdir(working_dir) do
      # Analyze the arguments
      if arguments[0] == '--readfile'
        posts_dir = Pathname.new('posts')
        my_file = posts_dir + 'myfile'
        puts my_file.read
      end
    end
  end
end

# Start the command without mockups if the ruby script is called directly
if __FILE__ == $PROGRAM_NAME
  MyCommand.new.execute
end

:

require 'pathname'
require 'tmpdir'
require 'stringio'

def setup
  @working_dir = Pathname.new(Dir.mktmpdir('mycommand'))
  @output = StringIO.new
  @error = StringIO.new

  @command = MyCommand.new(:working_dir => @working_dir, :output => @output, :error => @error)
end

def test_some_stuff
  @command.execute(['--readfile'])

  # ...
end

def teardown
  @working_dir.rmtree
end

( Pathname, - API- Ruby StringIO, STDOUT, -, )

acutal @working_dir :

path = @working_dir + 'posts' + 'myfile'
path.exist?
path.file?
path.directory?
path.read == "abc\n"
+2

(, , ), , , . , , . , ( 1 300 )

, , , - , , , .

+1

Source: https://habr.com/ru/post/1793282/


All Articles