Home > Blockchain >  Hot to test ruby script with rspec
Hot to test ruby script with rspec

Time:10-12

How to run/test ruby script in RSpec tests?

A simple example of a testing argument of called script

# frozen_string_literal: true

begin
  raise Errors::NoArgumentError                 if ARGV.count.zero?
rescue Errors => e
  puts e.message
  abort
end

file  = File.open(ARGV[0], 'r')
# Do something with file...

I tried to test with:

  it 'should throw no argument error' do
    expect {
     load('bin/script.rb') # Or system()
    }.to raise_error(Errors::NoArgumentError)
  end

CodePudding user response:

I would recommend to split the script and the application code into two different files which will make it a lot easier to test because you don't need to load the file and can easily inject arguments.

# script.rb
exit(Cli.run(ARGV)

and then have a Cli class which you can call

# cli.rb
class Cli
  def self.run(args)
    new(args).run
  end

  def initialize(args)
    @args = args
  end

  def run
    raise Errors::NoArgumentError if @args.count.zero?
    File.open(@args[0], 'r')
    0 # exit code
  rescue Errors => e
    puts e.message
    1 # exit code
  end
end

And then you can easily test this like

it 'should throw no argument error with no args provided' do
  expect {
    Cli.run([])
  }.to raise_error(Errors::NoArgumentError)
end

it 'should throw X if file does not exist' do
  expect {
    Cli.run(["not_existent"])
  }.to raise_error(Errors::NoArgumentError)
end
  • Related