From within a controller test, I can call a function in the controller like
this:
get :index
but how do I call a function in a different controller?
I want to do this for a couple reasons.
First I want to have my tests do a “real” login through my “user”
controller.
Second, my app supports redirects back to “where you were.” For
instance, if
a user goes to url A, then to url B, they might be redirected back to A.
If,
instead, they go to C, then to B, they’ll be redirected back to C. To
test
this functionality, I need to set the “original” URL by going to an URL
in
another controller (the A or C), then go to the URL in the controller
under
test, and see that the redirect is to the original controller.
I wrote some cheesy code to approximate the behavior I want. It looks
like
this:
class Test::Unit::TestCase
#MES- Send an HTTP message to the indicated controller via
the indicated method
def http_to_controller(method, controller, action, params)
#MES- Store the current controller
backup_controller = @controller
begin
#MES- Swap in the indicated controller
@controller = controller
#MES- Send the HTTP message
self.send(method, action, params)
ensure
#MES- Swap back in the controller
@controller = backup_controller
#MES- Remake the request, but save the session
new_req = ActionController::TestRequest.new
new_req.session = @request.session
@request = new_req
end
end
end
and it can be called like this:
http_to_controller(:get, UserController.new, :show, { :id => user_id })
But it doesn’t work quite right. In particular, the URLs are not always
quite right, so a call to @request.request_uri returns an old value (in
this
example, it wouldn’t return the URL to the UserController method, it’d
return the URL to whatever the previous call was.
Any ideas? It seems like there’s got to be a cleaner and safer way to do
this, but I haven’t been able to come up with it.