Skip to content

Instantly share code, notes, and snippets.

@lgs
Forked from delba/application_controller.rb
Created March 17, 2016 09:57
Show Gist options
  • Save lgs/5e25d52bc6e64070b729 to your computer and use it in GitHub Desktop.
Save lgs/5e25d52bc6e64070b729 to your computer and use it in GitHub Desktop.
use current_user in controller tests
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
private
def signed_in?
!!session[:user_id]
end
helper_method :signed_in?
def current_user=(user)
session[:user_id] = user.id
end
def current_user
return unless signed_in?
@current_user ||= User.find(session[:user_id])
end
helper_method :current_user
end
class SessionsController < ApplicationController
def create
user = User.find_by(email: params[:email])
if user.try(:authenticate, params[:password])
self.current_user = user
redirect_to root_url
else
flash.now[:notice] = 'Wrong email/password combination'
render :new
end
end
end
require 'test_helper'
class SessionsControllerTest < ActionController::TestCase
self.use_instantiated_fixtures = true
test "sign in with valid credentials" do
sign_in @sophie
assert_equal @sophie, current_user
end
test "sign in with invalid credentials" do
sign_in @sophie, password: 'wrong'
assert_nil current_user
end
private
def sign_in(user, password: 'secret')
post :create, email: user.email, password: password
end
end
ENV["RAILS_ENV"] ||= "test"
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
class ActiveSupport::TestCase
ActiveRecord::Migration.check_pending!
fixtures :all
end
class ActionController::TestCase
def current_user
@controller.send(:current_user)
end
private :current_user
end
sophie:
email: [email protected]
password_digest: <%= BCrypt::Password.create('secret') %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment