14.4 Integration Testing of Applications 14.2 Unit Testing of Models
edit app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
layout "store"
before_filter :authorize, :except => :login
#...
protected
def authorize
unless User.find_by_id(session[:user_id])
flash[:notice] = "Please log in"
redirect_to :controller => 'admin', :action => 'login'
end
end
def set_locale
session[:locale] = params[:locale] if params[:locale]
I18n.locale = session[:locale] || I18n.default_locale
locale_path = "#{LOCALES_DIRECTORY}#{I18n.locale}.yml"
unless I18n.load_path.include? locale_path
I18n.load_path << locale_path
I18n.backend.send(:init_translations)
end
rescue Exception => err
logger.error err
flash.now[:notice] = "#{I18n.locale} translation not available"
I18n.load_path -= [locale_path]
I18n.locale = session[:locale] = I18n.default_locale
end
end
edit test/functional/admin_controller_test.rb
require 'test_helper'
class AdminControllerTest < ActionController::TestCase
fixtures :users
# Replace this with your real tests.
test "the truth" do
assert true
end
if false
test "index" do
get :index
assert_response :success
end
end
test "index without user" do
get :index
assert_redirected_to :action => "login"
assert_equal "Please log in", flash[:notice]
end
test "index with user" do
get :index, {}, { :user_id => users(:dave).id }
assert_response :success
assert_template "index"
end
test "login" do
dave = users(:dave)
post :login, :name => dave.name, :password => 'secret'
assert_redirected_to :action => "index"
assert_equal dave.id, session[:user_id]
end
test "bad password" do
dave = users(:dave)
post :login, :name => dave.name, :password => 'wrong'
assert_template "login"
end
end
edit test/fixtures/users.yml
<% SALT = "NaCl" unless defined?(SALT) %>
dave:
name: dave
salt: <%= SALT %>
hashed_password: <%= User.encrypted_password('secret', SALT) %>
ruby -I test test/functional/admin_controller_test.rb
Loaded suite test/functional/admin_controller_test
Started
.....
Finished in 0.09424 seconds.
5 tests, 8 assertions, 0 failures, 0 errors
14.4 Integration Testing of Applications 14.2 Unit Testing of Models