MiniTest:如何测试exit关键字

时间:2018-09-05 13:55:37

标签: ruby exit minitest

我有一个“退出”方法:

def quit
  puts "Good bye!"
  exit 
end

我想做的是做一个迷你测试断言,说quit方法确实退出了,我尝试过的任何方法都没有用。寻找输入。预先感谢!

2 个答案:

答案 0 :(得分:3)

从技术上来说以下是测试实现而非行为,但这可能已经足够了,因为实际行为应由ruby的核心语言测试覆盖:

require 'minitest/autorun'

def quit
  puts "Good bye!"
  exit 
end

describe 'quit' do
  it 'ends the process' do
    assert_raises SystemExit do 
      quit
    end
  end
end

请注意,这是一种不常见的情况;通常不建议从rescueSystemExit,因为这可能会导致各种奇怪的行为-例如如果您在运行过程中手动杀死该进程,则该测试实际上会通过(并且该进程本身实际上不会终止)!

如果您使用的是rspec,则实现将类似:

RSpec.describe 'quit' do
  it 'ends the process' do
    expect { quit }.to raise_error(SystemExit)
  end
end

答案 1 :(得分:2)

require "minitest/autorun"

def quit_42
  puts "Good bye!"
  exit 42
end

describe :exit_code do
  it "returns 42" do
    err = -> { quit_42 }.must_raise SystemExit
    err.status.must_equal 42
  end
end