lundi 27 février 2017

Receiving "ActionController::UrlGenerationError" when using named routes in test

In my config/routes.rb file, special routes for each user are set as follows:

resources :users do
  member do
    get :following, :followers, :teams
  end
end

The users controller contains and defines the respective following, followers and teams actions. The above resources should generate the following named routes:
following_user_path(), followers_user_path() and teams_user_path()

so that a request like get following_user_path(1) is equivalent to get /users/1/following

Since the users controller has a before filter associated to all of these actions that redirect to the login_url when the user is not logged in, I created tests like the test below:

test "should redirect followers when not logged in" do
  get followers_user_path(@user)
  assert_redirected_to login_url
end

However, when I run these tests, I receive the following error:

ERROR["test_should_redirect_followers_when_not_logged_in", UsersControllerTest, 1.2590469539973128]
 test_should_redirect_followers_when_not_logged_in#UsersControllerTest (1.26s)
ActionController::UrlGenerationError:         ActionController::UrlGenerationError: No route matches {:action=>"/users/762146111/followers", :controller=>"users"}
            test/controllers/users_controller_test.rb:77:in `block in <class:UsersControllerTest>'

The test passes when I use instead the following code:

test "should redirect followers when not logged in" do
  get :followers, params: { id: @user }
  assert_redirected_to login_url
end

I previously upgraded my application from Rails 4.2.2 to Rails 5.0.0.1 and I thought of mentioning this change. I know no other reasons why my tests fail when I use the named routes. Not considering this issue, my application works as expected, but I would like my named routes be available also in tests.

Aucun commentaire:

Enregistrer un commentaire