Making Tests Work with RSpec and Capybara in Rails

This past weekend I worked on the next section which was Rails II – basically we were to build the project and utilize testing to make sure it would work. There were different levels one could do to complete this assignment: 1. Do the assignment without testing 2. Make the assignment work with the testing they provided on the platform or 3. Write your own tests in addition to the ones that were provided. This assignment was like a series, in which we add onto the project with each assignment we complete. We were given a wireframe and the tests and were set loose.

The project is to login or register a user, upon logon this page will redirect to the users Secrets page where a user can create their own secret, show the secrets they’ve liked or delete secrets they’ve created. There was a Secrets page which displayed all the secrets, allowed only the user logged in to like/unlike or delete the secrets they’ve created (much like the users’ show page). Along the way, we also implemented User Authentication (which is how we allowed only the logged in user to navigate through the app)

It turns out it’s as easy as putting a method at the top of our UsersController:

before_action :require_login, except: [:new, :create]

The above code states that before you do anything, go to the require_login method which verifies if the user is indeed the user that’s logged in via the session[:user_id] variable. The exception in this case is the new and create methods — A user should be able to access the page to create a new session by logging in or registering as a new user.

In the Secrets Controller, we added this code:

before_action :require_login, only: [:index, :create, :destroy]

Which states that before you go to any method, make sure that the user trying to access the page is indeed the user that’s logged in (as above) and if not, redirect that person back to the page where they can create an account or login. In the only:  tag, we allow only the logged in user access the index, create and destroy methods. We created tests for these methods.

Next up is the User Authorization. This is the code that’s put at the top of our UsersController:

before_action :require_correct_user, only: [:show, :edit, :update, :destroy]

The require_correct_user is used to define if the user is the one logged in and if not, redirects that user to their own page so they aren’t able to view everyone else’s pages…here’s the method defined in the application_controller:

  def require_correct_user

    user = User.find(params[:id])

    redirect_to “/users/#{current_user.id}” if current_user != user

  end

The last part of this section was to create our own tests for the User Authorization and User Authentication. I’ll leave you with some snippets of my tests:

likes_controller_spec

likes_controller_spec_2