In a functional test, I want to call an action in another controller.
Routing decides which controller receives which requests. Often, there is more than one route to each controller, and different routes can be served by different actions. Each action's purpose is to collect information to provide it to a view.
The Rails controller is the logical center of your application. It coordinates the interaction between the user, the views, and the model. The controller is also a home to a number of important ancillary services. It is responsible for routing external requests to internal actions.
When writing controllers in Ruby on rails, using before_action (used to be called before_filter in earlier versions) is your bread-and-butter for structuring your business logic in a useful way. It's what you want to use to "prepare" the data necessary before the action executes.
You have to set the @controller
instance variable to the controller that should be used.
Example usage in a test helper method (of course you don't need to use it in a helper method - you can use it right in your test method):
def login(user_name='user', password='asdfasdf')
# save the current controller
old_controller = @controller
# use the login controller
@controller = LoginController.new # <---
# perform the actual login
post :login, user_login: user_name, user_password: password
assert_redirected_to controller: 'welcome', action: 'index'
# check the users's values in the session
assert_not_nil session[:user]
assert_equal session[:user], User.find_by_login('user')
# restore the original controller
@controller = old_controller
end
Answered by Jonathan Weiss, in 2006 on ruby-forum: post() to other controller in functional test?
It should be noted that, for the most part (probably >99.9% of the time), one should use integration tests (aka feature tests) for testing inter-controller behaviour.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With