This isn't a problem with assert_raises
, that continues to work just fine. The issue you are having is that the exception you are raising within your Rails app is getting handled by your Rails app and not propagating out to your test. Calling get '/missing'
is raising the AbstractController::ActionNotFound
error, but then your app handles the error and returns an appropriate response (404 or 500) to the client (your test).
Okay, so how would you go about testing that your controller really did raise the error you are expecting? Normally you would just use an ActionController::TestCase
test to test your controllers. But, when you call an action on a controller that doesn't in ActionController::TestCase
you get a different error. So the following:
require "test_helper"
class TestControllerTest < ActionController::TestCase
def test_missing
assert_raises AbstractController::ActionNotFound do
get :missing
end
end
end
Produces the following output:
1) Failure:
TestControllerTest#test_missing [test/controllers/test_controller_test.rb:6]:
[AbstractController::ActionNotFound] exception expected, not
Class: <ActionController::UrlGenerationError>
Message: <"No route matches {:action=>\"missing\", :controller=>\"test\"}">
---Backtrace---
test/controllers/test_controller_test.rb:7:in `block in test_missing'
test/controllers/test_controller_test.rb:6:in `test_missing'
---------------
The reason is because ActionController::TestCase
is aware of the routes and won't allow calling an action that is not in the routes. But that is exactly what you are trying to test. And, I assume why you aren't using ActionController::TestCase
.
At this point I wonder if you aren't testing something you shouldn't. Perhaps you should allow Rails to do its job and trust that it behaves correctly. But hey, we've come this far, why not just go all the way and test what Rails tests anyway. Instead of making the call through the full Rails app, let's try calling the TestController
directly. If we create a new instance of the controller we can ask it to handle an action even if that action is not defined on the controller. But to do this we will have to dive deep into how ActionController works and make use of the AbstractController#process
method:
require "test_helper"
class TestControllerTest < Minitest::Test
def test_missing
assert_raises AbstractController::ActionNotFound do
TestController.new.process :missing
end
end
end
Now we are asking the controller to process an action that doesn't exist and testing that the controller behaves as expected. Yay?