Hi,
I’m puzzled why my functional tests are failing. I have the following
test:
assert_raise ActiveRecord::RecordInvalid do
post :create, :page_id => id_from_fixture, :body => “bla bla”
end
assert_redirected_to my_error_path
In my controller, I am catching the error:
def create
begin @page = current_user.pages.find(params[:page_id])
do_some_stuff
rescue ActiveRecord::RecordInvalid
redirect_to my_error_path
end
end
When I run the test, it fails on the grounds that ‘nothing was
raised’. But I know for sure that the error was raised, because when I
remove the assert_raise test and just check the redirect, the test
passes.
Is it because I already rescue in the controller that the assertion
doesn’t see the error anymore?
A mistake in the above example: I’m checking
ActiveRecord::RecordNotFound of course (I have actually more rescue
clauses, including the ActiveRecord:RecordInvalid one).
Anyway, the test is failing regardless which rescue clause I enter.
Ganesh,
Thanks for the explanation. I thought it might be related to me
handling the exception in the controller.
But if I don’t handle it in the controller, how do I handle it? In the
example you give, the controller just throws the exception and it
never gets handled by my application, right.
My guess would be to make a special exception handler in the
application controller? But which method do I need to override to make
my own rescue handler? I’m only familiar with the begin/rescue
construct and I must say the books and documentation I have used up to
now are very succinct on exception handling. Always a weak point I
find, where error handling is actually the most important thing!
You have handled the RecordInvalid exception in the controller itself.
Once you have handled the exception you cannot test it using
assert_raise
Ex below:
def boom
begin
raise Exception.new(“Blah”)
rescue Exception => e
puts "Exception Caught " + e
end
end
require “test/unit”
class MyTest < Test::Unit::TestCase
def test_boom
assert_raise Exception do
boom
end
end
end
--------------------------------------------------------------------
gg@ubuntu:~/Work/Ruby$ ruby gg.rb
Loaded suite gg
Started
Exception Caught Blah
F
Finished in 0.06206 seconds.
Failure:
test_boom(MyTest) [gg.rb:13]:
exception expected but none was thrown.
Try the same test without handling the exception
--------------------------------------------------------------------
def boom
begin
raise Exception.new(“Blah”) #rescue Exception => e
puts "Exception Caught " + e
end
end
require “test/unit”
class MyTest < Test::Unit::TestCase
def test_boom
assert_raise Exception do
boom
end
end
end
--------------------------------------------------------------------
gg@ubuntu:~/Work/Ruby$ ruby gg.rb
Loaded suite gg
Started
.
Finished in 0.002276 seconds.