Ensuring Exclusive Current_User Access in Rails

Here’s our scenario. We have Users who can create and manage a list of stores like Kmart and Kroger’s.  Store is a nested resource of Users with a path of


Our objective is to make sure a user with user_id 15 cannot load /users/37/stores and muck with user 37’s store list. Exclusive Current_User access to prevent a really bad day for the web support group.

The Controller

To ensure that only a user with user_id 37 can load /users/37/stores and its actions we’ll specify two access requirements in the StoresController. 1) the user must be signed in and 2) the correct user is the current_user having the :user_id in the path.  We do that with :signed_in_user and :correct_user.

:signed_in_user is located in sessions_helper.rb

:correct_user is a private method in the controller.

The Rspec Tests

Okay, that should do it, but what will the Rspec tests look like?  We’ll create two users, :user (our current user) and :other_user. The key is using a controller stub to assign the controller’s :current_user with our valid user. Then we access a controller action with other_user, at which point, because of our StoresController :correct_user method we should be redirected to the home page.

Using Shared_Examples_For

As a sidebar, we’re also using a shared_examples_for group to make our tests more DRY, passing each controller action as a parameter. 

It’s good to know that User 37’s store list is now secure!