]> git.donarmstrong.com Git - dsa-puppet.git/blob - modules/stdlib/spec/lib/puppet_spec/matchers.rb
upgrade to concat 2.0.0
[dsa-puppet.git] / modules / stdlib / spec / lib / puppet_spec / matchers.rb
1 require 'stringio'
2
3 ########################################################################
4 # Backward compatibility for Jenkins outdated environment.
5 module RSpec
6   module Matchers
7     module BlockAliases
8       alias_method :to,     :should      unless method_defined? :to
9       alias_method :to_not, :should_not  unless method_defined? :to_not
10       alias_method :not_to, :should_not  unless method_defined? :not_to
11     end
12   end
13 end
14
15
16 ########################################################################
17 # Custom matchers...
18 RSpec::Matchers.define :have_matching_element do |expected|
19   match do |actual|
20     actual.any? { |item| item =~ expected }
21   end
22 end
23
24
25 RSpec::Matchers.define :exit_with do |expected|
26   actual = nil
27   match do |block|
28     begin
29       block.call
30     rescue SystemExit => e
31       actual = e.status
32     end
33     actual and actual == expected
34   end
35   failure_message_for_should do |block|
36     "expected exit with code #{expected} but " +
37       (actual.nil? ? " exit was not called" : "we exited with #{actual} instead")
38   end
39   failure_message_for_should_not do |block|
40     "expected that exit would not be called with #{expected}"
41   end
42   description do
43     "expect exit with #{expected}"
44   end
45 end
46
47
48 RSpec::Matchers.define :have_printed do |expected|
49   match do |block|
50     $stderr = $stdout = StringIO.new
51
52     begin
53       block.call
54     ensure
55       $stdout.rewind
56       @actual = $stdout.read
57
58       $stdout = STDOUT
59       $stderr = STDERR
60     end
61
62     if @actual then
63       case expected
64       when String
65         @actual.include? expected
66       when Regexp
67         expected.match @actual
68       else
69         raise ArgumentError, "No idea how to match a #{@actual.class.name}"
70       end
71     end
72   end
73
74   failure_message_for_should do |actual|
75     if actual.nil? then
76       "expected #{expected.inspect}, but nothing was printed"
77     else
78       "expected #{expected.inspect} to be printed; got:\n#{actual}"
79     end
80   end
81
82   description do
83     "expect #{expected.inspect} to be printed"
84   end
85
86   diffable
87 end