forked from thoughtbot/shoulda-matchers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rescue_from_matcher.rb
115 lines (101 loc) · 3.04 KB
/
rescue_from_matcher.rb
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
module Shoulda
module Matchers
module ActionController
# The `rescue_from` matcher tests usage of the `rescue_from` macro. It
# asserts that an exception and method are present in the list of
# exception handlers, and that the handler method exists.
#
# class ApplicationController < ActionController::Base
# rescue_from ActiveRecord::RecordNotFound, with: :handle_not_found
#
# private
#
# def handle_not_found
# # ...
# end
# end
#
# # RSpec
# RSpec.describe ApplicationController, type: :controller do
# it do
# should rescue_from(ActiveRecord::RecordNotFound).
# with(:handle_not_found)
# end
# end
#
# # Minitest (Shoulda)
# class ApplicationControllerTest < ActionController::TestCase
# should rescue_from(ActiveRecord::RecordNotFound).
# with(:handle_not_found)
# end
#
# @return [RescueFromMatcher]
#
def rescue_from(exception)
RescueFromMatcher.new exception
end
# @private
class RescueFromMatcher
def initialize(exception)
@exception = exception
@expected_method = nil
@controller = nil
end
def with(method)
@expected_method = method
self
end
def matches?(controller)
@controller = controller
rescues_from_exception? && method_name_matches? && handler_exists?
end
def description
description = "rescue from #{exception}"
description << " with ##{expected_method}" if expected_method
description
end
def failure_message
"Expected #{expectation}"
end
def failure_message_when_negated
"Did not expect #{expectation}"
end
protected
attr_reader :controller, :exception, :expected_method, :handlers
def expectation
expectation = "#{controller} to rescue from #{exception}"
if expected_method && !method_name_matches?
expectation << " with ##{expected_method}"
end
unless handler_exists?
expectation << " but #{controller} does not respond to"\
" #{expected_method}"
end
expectation
end
def rescues_from_exception?
@handlers = controller.rescue_handlers.select do |handler|
handler.first == exception.to_s
end
handlers.any?
end
def method_name_matches?
if expected_method.present?
handlers.any? do |handler|
handler.last == expected_method
end
else
true
end
end
def handler_exists?
if expected_method.present?
controller.respond_to? expected_method, true
else
true
end
end
end
end
end
end