I'm following the Rails Tutorial by Michael Hartl and am running into a problem I'm trying to get my head around. I have several tests failing indicating that "sign_in" is not a valid function.
It's declared here:
Rails Tutorial SessionsHelper.rb
You can see the UsersController
leverages the sign_in
method in the create
function here:
Rails Tutorial UsersController.rb
I have the same setup in place but my unit tests indicate that UsersController can't find the sign_in function. If I declare include SessionsHelper
UsersController.rb, my unit tests pass but obviously the sample app in RailsTutorial didn't have to do that so I'm wondering what I should be looking for to help debug this.
It looks like it should be automatically available, but it's not in my case.
For completeness, here is the relevant code from my dev environment:
module SessionsHelper
def sign_in(user)
remember_token = User.new_remember_token
cookies.permanent[:remember_token] = remember_token
user.update_attribute(:remember_token, User.digest(remember_token))
self.current_user = user
end
def current_user=(user)
@current_user = user
end
def current_user
remember_token = User.digest(cookies[:remember_token])
@current_user ||= User.find_by(remember_token: remember_token)
end
def signed_in?
!current_user.nil?
end
end
class UsersController < ApplicationController
def new
@user = User.new
end
def create
@user = User.new(user_params)
if @user.save
sign_in @user # unit tests indicate a failure to find sign_in here
flash[:success] = "Welcome to the Sample App!"
redirect_to @user
else
render 'new'
end
end
def show
@user = User.find(params[:id])
end
private
def user_params
params.require(:user).permit(:name, :email, :password, :password_confirmation)
end
end
You need to include the sessions helper for it to be available in the controller/view layers. The application code that you linked to does include the sessions helper, it just does so in the application_controller.rb
file as you can see here.
By default, helper methods are only available to their corresponding controller/views. This means that if you have a users_helper.rb
file in your app/helpers
folder, the methods defined there will be available to the users controller and user views by default.
If you want to use a method from a helper outside of its namespace, it has to be included at the scope that you want access to it. So including the SessionsHelper
in the users controller as you did in your solution would make it available to the users controller and views only. Including a helper in the application controller as done in the example app code makes the helper methods available to all controllers/views in the application.