Class: Spec::DSL::ExampleShouldRaiseHandler

Inherits:
Object
  • Object
show all
Defined in:
lib/spec/dsl/example_should_raise_handler.rb

Instance Method Summary collapse

Constructor Details

#initialize(file_and_line_number, opts) ⇒ ExampleShouldRaiseHandler

Returns a new instance of ExampleShouldRaiseHandler.



4
5
6
7
8
9
# File 'lib/spec/dsl/example_should_raise_handler.rb', line 4

def initialize(file_and_line_number, opts)
  @file_and_line_number = file_and_line_number
  @options = opts
  @expected_error_class = determine_error_class(opts)
  @expected_error_message = determine_error_message(opts)
end

Instance Method Details

#build_message(exception = nil) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
# File 'lib/spec/dsl/example_should_raise_handler.rb', line 32

def build_message(exception=nil)
  if @expected_error_message.nil?
    message = "example block expected #{@expected_error_class.to_s}"
  else
    message = "example block expected #{@expected_error_class.new(@expected_error_message.to_s).inspect}"
  end
  message << " but raised #{exception.inspect}" if exception
  message << " but nothing was raised" unless exception
  message << "\n"
  message << @file_and_line_number
end

#determine_error_class(opts) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
# File 'lib/spec/dsl/example_should_raise_handler.rb', line 11

def determine_error_class(opts)
  if candidate = opts[:should_raise]
    if candidate.is_a?(Class)
      return candidate
    elsif candidate.is_a?(Array)
      return candidate[0]
    else
      return Exception
    end
  end
end

#determine_error_message(opts) ⇒ Object



23
24
25
26
27
28
29
30
# File 'lib/spec/dsl/example_should_raise_handler.rb', line 23

def determine_error_message(opts)
  if candidate = opts[:should_raise]
    if candidate.is_a?(Array)
      return candidate[1]
    end
  end
  return nil
end

#error_matches?(error) ⇒ Boolean

Returns:

  • (Boolean)


44
45
46
47
48
49
50
51
52
53
54
# File 'lib/spec/dsl/example_should_raise_handler.rb', line 44

def error_matches?(error)
  return false unless error.kind_of?(@expected_error_class)
  unless @expected_error_message.nil?
    if @expected_error_message.is_a?(Regexp)
      return false unless error.message =~ @expected_error_message
    else
      return false unless error.message == @expected_error_message
    end
  end
  return true
end

#handle(errors) ⇒ Object



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/spec/dsl/example_should_raise_handler.rb', line 56

def handle(errors)
  if @expected_error_class
    if errors.empty?
      errors << Spec::Expectations::ExpectationNotMetError.new(build_message)
    else
      error_to_remove = errors.detect do |error|
        error_matches?(error)
      end
      if error_to_remove.nil?
        errors.insert(0,Spec::Expectations::ExpectationNotMetError.new(build_message(errors[0])))
      else
        errors.delete(error_to_remove)
      end
    end
  end
end