MiniTest:如何测试exit关键字

问题描述 投票:1回答:2

我有一个方法'退出':

def quit
  puts "Good bye!"
  exit 
end

我想要做的是做一个迷你测试断言,退出方法确实退出了,没有我尝试过的工作。寻找输入。提前致谢!

ruby exit minitest
2个回答
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

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
© www.soinside.com 2019 - 2024. All rights reserved.