/
respond_with_content_type_matcher.rb
83 lines (69 loc) · 2.44 KB
/
respond_with_content_type_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
require 'active_support/deprecation'
module Shoulda # :nodoc:
module Matchers
module ActionController # :nodoc:
# Ensures a controller responded with expected 'response' content type.
#
# You can pass an explicit content type such as 'application/rss+xml'
# or its symbolic equivalent :rss
# or a regular expression such as /rss/
#
# Example:
#
# it { should respond_with_content_type(:xml) }
# it { should respond_with_content_type(:csv) }
# it { should respond_with_content_type(:atom) }
# it { should respond_with_content_type(:yaml) }
# it { should respond_with_content_type(:text) }
# it { should respond_with_content_type('application/rss+xml') }
# it { should respond_with_content_type(/json/) }
def respond_with_content_type(content_type)
RespondWithContentTypeMatcher.new(content_type)
end
class RespondWithContentTypeMatcher # :nodoc:
def initialize(content_type)
ActiveSupport::Deprecation.warn 'The respond_with_content_type matcher is deprecated and will be removed in 2.0'
@content_type = look_up_content_type(content_type)
end
def description
"respond with content type of #{@content_type}"
end
def matches?(controller)
@controller = controller
content_type_matches_regexp? || content_type_matches_string?
end
def failure_message_for_should
"Expected #{expectation}"
end
def failure_message_for_should_not
"Did not expect #{expectation}"
end
protected
def content_type_matches_regexp?
if @content_type.is_a?(Regexp)
response_content_type =~ @content_type
end
end
def content_type_matches_string?
response_content_type == @content_type
end
def response_content_type
@controller.response.content_type.to_s
end
def look_up_by_extension(extension)
Mime::Type.lookup_by_extension(extension.to_s).to_s
end
def look_up_content_type(content_type)
if content_type.is_a?(Symbol)
look_up_by_extension(content_type)
else
content_type
end
end
def expectation
"content type to be #{@content_type}, but was #{response_content_type}"
end
end
end
end
end