1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
|
# frozen_string_literal: true
require 'stringio'
require 'rspec/expectations'
# Custom matchers...
RSpec::Matchers.define :have_matching_element do |expected|
match do |actual|
actual.any? { |item| item =~ expected }
end
end
RSpec::Matchers.define :exit_with do |expected|
actual = nil
match do |block|
begin
block.call
rescue SystemExit => e
actual = e.status
end
actual && actual == expected
end
failure_message_for_should do |_block|
"expected exit with code #{expected} but " +
(actual.nil? ? ' exit was not called' : "we exited with #{actual} instead")
end
failure_message_for_should_not do |_block|
"expected that exit would not be called with #{expected}"
end
description do
"expect exit with #{expected}"
end
end
RSpec::Matchers.define :have_printed do |expected|
match do |block|
$stderr = $stdout = StringIO.new
begin
block.call
ensure
$stdout.rewind
@actual = $stdout.read
$stdout = STDOUT
$stderr = STDERR
end
if @actual
case expected
when String
@actual.include? expected
when Regexp
expected.match @actual
else
raise ArgumentError, "No idea how to match a #{@actual.class.name}"
end
end
end
failure_message_for_should do |actual|
if actual.nil?
"expected #{expected.inspect}, but nothing was printed"
else
"expected #{expected.inspect} to be printed; got:\n#{actual}"
end
end
description do
"expect #{expected.inspect} to be printed"
end
diffable
end
|