Skip to content

Commit 48a663a

Browse files
author
Alex Egan
committed
modify error message when redirected but expecting to render a template
1 parent 5836988 commit 48a663a

File tree

2 files changed

+34
-2
lines changed

2 files changed

+34
-2
lines changed

lib/rspec/rails/matchers/have_rendered.rb

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,18 +9,32 @@ def initialize(scope, expected, message = nil)
99
@expected = Symbol === expected ? expected.to_s : expected
1010
@message = message
1111
@scope = scope
12+
@redirect_is = nil
1213
end
1314

1415
# @api private
1516
def matches?(*)
16-
match_unless_raises ActiveSupport::TestCase::Assertion do
17+
match_check = match_unless_raises ActiveSupport::TestCase::Assertion do
1718
@scope.assert_template expected, @message
1819
end
20+
check_redirect unless match_check
21+
match_check
22+
end
23+
24+
def check_redirect
25+
response = @scope.response
26+
return unless response.respond_to?(:redirect?) && response.redirect?
27+
@redirect_is = @scope.send(:normalize_argument_to_redirection, response.location)
1928
end
2029

2130
# @api private
2231
def failure_message
23-
rescued_exception.message
32+
if @redirect_is
33+
rescued_exception.message[/.* but /] +
34+
"was a redirect to <#{@redirect_is}>"
35+
else
36+
rescued_exception.message
37+
end
2438
end
2539

2640
# @api private

spec/rspec/rails/matchers/have_rendered_spec.rb

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,24 @@ def assert_template(*); raise "oops"; end
8888
end.to raise_exception("oops")
8989
end
9090
end
91+
92+
context "when fails with a redirect" do
93+
let(:response) { ActionController::TestResponse.new(302) }
94+
def assert_template(*)
95+
message = "expecting <'template_name'> but rendering with <[]>"
96+
raise ActiveSupport::TestCase::Assertion.new(message)
97+
end
98+
def normalize_argument_to_redirection(*)
99+
"http://test.host/widgets/1"
100+
end
101+
it "gives informative error message" do
102+
response = ActionController::TestResponse.new(302)
103+
response.location = "http://test.host/widgets/1"
104+
expect do
105+
expect(response).to send(template_expectation, "template_name")
106+
end.to raise_exception("expecting <'template_name'> but was a redirect to <http://test.host/widgets/1>")
107+
end
108+
end
91109
end
92110
end
93111
end

0 commit comments

Comments
 (0)