Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In a Rails controller test, how to access a different controller action?

In a functional test, I want to call an action in another controller.

like image 400
user664833 Avatar asked Mar 29 '14 01:03

user664833


People also ask

What decides which controller receives Ruby?

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.

What does controller do in Rails?

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.

What does before action do in Rails?

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.


1 Answers

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.

like image 100
user664833 Avatar answered Sep 28 '22 08:09

user664833