用rspec测试ruby脚本很热



如何在RSpec测试中运行/测试ruby脚本?

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...

我试着测试:

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

我建议将脚本和应用程序代码分成两个不同的文件,这将使它更容易测试,因为你不需要加载文件,可以很容易地注入参数。

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

然后有一个Cli类你可以叫它

# 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

然后你可以很容易地测试这个,比如

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

最新更新