1
0
Fork 0
mirror of https://github.com/heartcombo/devise.git synced 2022-11-09 12:18:31 -05:00

Configuring session and password controllers as engine, and getting integration tests from devise example app.

This commit is contained in:
Carlos A. da Silva 2009-10-07 21:46:40 -03:00
parent 0ba9980355
commit 7ce49cbbe8
60 changed files with 27590 additions and 69 deletions

View file

@ -0,0 +1,32 @@
class PasswordsController < ApplicationController
before_filter :require_no_authentication
def new
end
def create
@password = User.find_and_send_reset_password_instructions(params[:password][:email])
if !@password.new_record?
flash[:notice] = 'You will receive an email with instructions about how to reset your password in a few minutes.'
redirect_to new_session_path
else
render :new
end
end
def edit
@password = User.new
@password.perishable_token = params[:perishable_token]
end
def update
@password = User.find_and_reset_password(params[:password][:perishable_token],
params[:password][:password], params[:password][:password_confirmation])
if @password.errors.empty?
flash[:notice] = 'Your password was changed successfully.'
redirect_to new_session_path
else
render :edit
end
end
end

View file

@ -0,0 +1,15 @@
class SessionsController < ApplicationController
before_filter :authenticate!, :except => :new
before_filter :require_no_authentication, :only => :new
def new
end
def create
redirect_to root_path if authenticated?
end
def destroy
redirect_to :action => :new if logout
end
end

View file

@ -0,0 +1,12 @@
<h2>Change your password</h2>
<%= error_messages_for :password %>
<% form_for :password, :url => password_path, :html => { :method => :put } do |f| %>
<%= f.hidden_field :perishable_token %>
<p><%= f.label :password %></p>
<p><%= f.password_field :password %></p>
<p><%= f.label :password_confirmation %></p>
<p><%= f.password_field :password_confirmation %></p>
<p class="submit"><%= f.submit "Change my password" %></p>
<% end %>

View file

@ -0,0 +1,11 @@
<h2>Forgot password</h2>
<%= error_messages_for :password %>
<% form_for :password, :url => password_path do |f| %>
<p><%= f.label :email %></p>
<p><%= f.text_field :email %></p>
<p class="submit"><%= f.submit "Send me reset password instructions" %></p>
<% end %>
<%= link_to 'Sign in', new_session_path %>

View file

@ -0,0 +1,13 @@
<h2>Sign in</h2>
<%= warden.message if warden.message.present? %>
<% form_for :session, :url => session_path do |f| -%>
<p><%= f.label :email %></p>
<p><%= f.text_field :email %></p>
<p><%= f.label :password %></p>
<p><%= f.password_field :password %></p>
<p class='submit'><%= f.submit 'Sign In' %></p>
<% end -%>
<%= link_to "Forgot password?", new_password_path %>

4
config/routes.rb Normal file
View file

@ -0,0 +1,4 @@
ActionController::Routing::Routes.draw do |map|
map.resource :session, :only => [:new, :create, :destroy]
map.resource :password, :only => [:new, :create, :edit, :update]
end

View file

@ -1,3 +1,19 @@
begin
require 'warden'
rescue
gem 'hassox-warden'
require 'warden'
end
begin
require 'rails_warden'
rescue
gem 'hassox-rails_warden'
require 'rails_warden'
end
require 'devise/initializers/warden'
require 'devise/models/authenticable'
require 'devise/models/perishable'
require 'devise/models/confirmable'
@ -5,3 +21,7 @@ require 'devise/models/recoverable'
require 'devise/models/validatable'
require 'devise/mailers/notifier'
class ActionController::Base
include Devise::Controllers::Authenticable
end

View file

@ -0,0 +1,10 @@
module Devise
module Controllers
module Authenticable
def require_no_authentication
redirect_to root_path if authenticated?
end
end
end
end

View file

@ -0,0 +1,38 @@
# Adds RailsWarden Manager to Rails middleware stack, configuring default devise
# strategy and also the controller who will manage not authenticated users.
#
Rails.configuration.middleware.use RailsWarden::Manager do |manager|
manager.default_strategies :devise
manager.failure_app = SessionsController
end
# Configure RailsWarden to call new action inside failure controller when no
# user is authenticated.
#
RailsWarden.unauthenticated_action = 'new'
# Default strategy for signing in a user, based on his email and password.
# If no email and no password are present, no authentication is tryed.
#
Warden::Strategies.add(:devise) do
# Validate params before authenticating a user. If both email and password are
# not present, no authentication is attempted.
#
def valid?
params[:session] ||= {}
params[:session][:email].present? && params[:session][:password].present?
end
# Authenticate a user based on email and password params, returning to warden
# success and the authenticated user if everything is okay. Otherwise tell
# warden the authentication was failed.
#
def authenticate!
if user = User.authenticate(params[:session][:email], params[:session][:password])
success!(user)
else
fail!(I18n.t(:failed_login, :scope => :devise, :default => 'Invalid email or password'))
end
end
end

View file

@ -50,8 +50,8 @@ module Devise
# If no user is found, returns a new user
# If the user is already confirmed, create an error for the user
#
def find_and_confirm(confirmation_token)
confirmable = find_or_initialize_by_perishable_token(confirmation_token)
def find_and_confirm(perishable_token)
confirmable = find_or_initialize_by_perishable_token(perishable_token)
unless confirmable.new_record?
confirmable.confirm!
else

22
test/assertions_helper.rb Normal file
View file

@ -0,0 +1,22 @@
class ActiveSupport::TestCase
def assert_not(assertion)
assert !assertion
end
def assert_blank(assertion)
assert assertion.blank?
end
def assert_not_blank(assertion)
assert !assertion.blank?
end
alias :assert_present :assert_not_blank
def assert_email_sent(&block)
assert_difference('ActionMailer::Base.deliveries.size') { yield }
end
def assert_email_not_sent(&block)
assert_no_difference('ActionMailer::Base.deliveries.size') { yield }
end
end

View file

@ -0,0 +1,66 @@
require 'test_helper'
class AuthenticationTest < ActionController::IntegrationTest
test 'not authenticated user should load up sign in form' do
visit '/'
assert_response :success
assert_template 'sessions/new'
end
test 'signing in with invalid email should return to sign in form with error message' do
sign_in do
fill_in 'email', :with => 'wrongemail@test.com'
end
assert_response :success
assert_template 'sessions/new'
assert_contain 'Invalid email or password'
assert !warden.authenticated?
end
test 'signing in with invalid pasword should return to sign in form with error message' do
sign_in do
fill_in 'password', :with => 'abcdef'
end
assert_response :success
assert_template 'sessions/new'
assert_contain 'Invalid email or password'
assert !warden.authenticated?
end
test 'not confirmed user should not be able to login' do
sign_in(:confirm => false)
assert_contain 'Invalid email or password'
assert !warden.authenticated?
end
test 'already confirmed user should be able to sign in successfully' do
sign_in
assert_response :success
assert_template 'home/index'
assert_not_contain 'Sign In'
assert warden.authenticated?
end
test 'not authenticated user should not be able to sign out' do
delete '/session'
assert_response :success
assert_template 'sessions/new'
assert !warden.authenticated?
end
test 'authenticated user should be able to sign out' do
sign_in
assert warden.authenticated?
delete '/session'
assert_response :redirect
assert_redirected_to new_session_path
assert !warden.authenticated?
end
end

View file

@ -0,0 +1,121 @@
require 'test_helper'
class PasswordRecoveryTest < ActionController::IntegrationTest
def visit_new_password_path
visit '/session/new'
click_link 'Forgot password?'
end
def request_forgot_password(&block)
visit_new_password_path
fill_in 'email', :with => 'test@test.com'
yield if block_given?
click_button 'Send me reset password instructions'
end
test 'authenticated user should not be able to visit forgot password page' do
sign_in
get new_password_path
assert_response :redirect
assert_redirected_to root_path
assert warden.authenticated?
end
test 'not authenticated user should be able to visit forgot password page' do
visit_new_password_path
assert_response :success
assert_template 'passwords/new'
assert !warden.authenticated?
end
test 'not authenticated user should be able to request a forgot password' do
create_user
request_forgot_password
assert_template 'sessions/new'
# TODO: what's going on with webrat? It's not detecting redirects
# assert_response :redirect
# assert_redirected_to new_session_path
assert_contain 'You will receive an email with instructions about how to reset your password in a few minutes.'
end
test 'not authenticated user with invalid email should receive an error message' do
request_forgot_password do
fill_in 'email', :with => 'invalid.test@test.com'
end
assert_response :success
assert_template 'passwords/new'
assert_have_selector 'input[type=text][value=\'invalid.test@test.com\']'
assert_contain 'Email not found'
end
# test 'request forgot password should send an email to the user' do
# ActionMailer::Base.deliveries = []
# request_forgot_password
# assert_equal 1, ActionMailer::Base.deliveries.size
# end
test 'authenticated user should not be able to visit edit password page' do
sign_in
get edit_password_path
assert_response :redirect
assert_redirected_to root_path
assert warden.authenticated?
end
test 'not authenticated with invalid perishable token should not be able to change his password' do
create_user
visit edit_password_path(:perishable_token => 'invalid_perishable')
assert_response :success
assert_template 'passwords/edit'
fill_in 'Password', :with => '987654321'
fill_in 'Password confirmation', :with => '987654321'
click_button 'Change my password'
assert_response :success
assert_template 'passwords/edit'
assert_have_selector '#errorExplanation'
assert_contain 'invalid confirmation'
assert !@user.reload.valid_password?('987654321')
end
test 'not authenticated with valid perisable token but invalid password should not be able to change his password' do
create_user
visit edit_password_path(:perishable_token => @user.perishable_token)
fill_in 'Password', :with => '987654321'
fill_in 'Password confirmation', :with => 'other_password'
click_button 'Change my password'
assert_response :success
assert_template 'passwords/edit'
assert_have_selector '#errorExplanation'
assert_contain 'Password doesn\'t match confirmation'
assert !@user.reload.valid_password?('987654321')
end
test 'not authenticated with valid data should be able to change his password' do
create_user
visit edit_password_path(:perishable_token => @user.perishable_token)
fill_in 'Password', :with => '987654321'
fill_in 'Password confirmation', :with => '987654321'
click_button 'Change my password'
# TODO: revisit this
assert_template 'sessions/new'
# assert_response :redirect
# assert_redirected_to new_session_path
assert_contain 'Your password was changed successfully.'
assert @user.reload.valid_password?('987654321')
end
end

View file

@ -0,0 +1,25 @@
class ActionController::IntegrationTest
def warden
request.env['warden']
end
def create_user(options={})
@user ||= begin
user = User.create!(
:email => 'test@test.com', :password => '123456', :password_confirmation => '123456'
)
user.confirm! unless options[:confirm] == false
user
end
end
def sign_in(options={}, &block)
create_user(options)
visit '/session/new'
fill_in 'email', :with => 'test@test.com'
fill_in 'password', :with => '123456'
yield if block_given?
click_button 'Sign In'
end
end

108
test/model_builder.rb Normal file
View file

@ -0,0 +1,108 @@
# Shoulda model builder
#
class ActiveSupport::TestCase
def create_table(table_name, &block)
connection = ActiveRecord::Base.connection
begin
connection.execute("DROP TABLE IF EXISTS #{table_name}")
connection.create_table(table_name, &block)
@created_tables ||= []
@created_tables << table_name
connection
rescue Exception => e
connection.execute("DROP TABLE IF EXISTS #{table_name}")
raise e
end
end
def define_constant(class_name, base, &block)
class_name = class_name.to_s.camelize
klass = Class.new(base)
Object.const_set(class_name, klass)
klass.class_eval(&block) if block_given?
@defined_constants ||= []
@defined_constants << class_name
klass
end
def define_model_class(class_name, &block)
define_constant(class_name, ActiveRecord::Base, &block)
end
def define_model(name, columns = {}, &block)
class_name = name.to_s.pluralize.classify
table_name = class_name.tableize
create_table(table_name) do |table|
columns.each do |name, type|
table.column name, type
end
end
define_model_class(class_name, &block)
end
def define_controller(class_name, &block)
class_name = class_name.to_s
class_name << 'Controller' unless class_name =~ /Controller$/
define_constant(class_name, ActionController::Base, &block)
end
def define_routes(&block)
@replaced_routes = ActionController::Routing::Routes
new_routes = ActionController::Routing::RouteSet.new
silence_warnings do
ActionController::Routing.const_set('Routes', new_routes)
end
new_routes.draw(&block)
end
def build_response(&block)
klass = define_controller('Examples')
block ||= lambda { render :nothing => true }
klass.class_eval { define_method(:example, &block) }
define_routes do |map|
map.connect 'examples', :controller => 'examples', :action => 'example'
end
@controller = klass.new
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
get :example
@controller
end
def teardown_with_models
if @defined_constants
@defined_constants.each do |class_name|
Object.send(:remove_const, class_name)
end
end
if @created_tables
@created_tables.each do |table_name|
ActiveRecord::Base.
connection.
execute("DROP TABLE IF EXISTS #{table_name}")
end
end
if @replaced_routes
ActionController::Routing::Routes.clear!
silence_warnings do
ActionController::Routing.const_set('Routes', @replaced_routes)
end
@replaced_routes.reload!
end
teardown_without_models
end
alias_method :teardown_without_models, :teardown
alias_method :teardown, :teardown_with_models
end

View file

@ -104,7 +104,8 @@ class AuthenticableTest < ActiveSupport::TestCase
end
test 'should authenticate a valid user with email and password and return it' do
user = create_user
user = User.create!(valid_attributes)
User.any_instance.stubs(:confirmed?).returns(true)
authenticated_user = User.authenticate(user.email, user.password)
assert_equal authenticated_user, user
end

View file

@ -9,18 +9,18 @@ class RecoverableTest < ActiveSupport::TestCase
end
test 'should reset password and password confirmation from params' do
@user.reset_password('56789', '98765')
assert_equal '56789', @user.password
assert_equal '98765', @user.password_confirmation
@user.reset_password('123456789', '987654321')
assert_equal '123456789', @user.password
assert_equal '987654321', @user.password_confirmation
end
test 'should reset password and save the record' do
assert @user.reset_password!('56789', '56789')
assert @user.reset_password!('123456789', '123456789')
end
test 'should not reset password with invalid data' do
@user.stubs(:valid?).returns(false)
assert_not @user.reset_password!('56789', '98765')
assert_not @user.reset_password!('123456789', '987654321')
end
test 'should reset perishable token and send instructions by email' do
@ -87,4 +87,3 @@ class RecoverableTest < ActiveSupport::TestCase
assert @user.valid_password?('new_password')
end
end

31
test/models_helper.rb Normal file
View file

@ -0,0 +1,31 @@
class ActiveSupport::TestCase
def setup_mailer
ActionMailer::Base.deliveries = []
end
# Helpers for creating new users
#
def generate_unique_email
@@email_count ||= 0
@@email_count += 1
"test#{@@email_count}@email.com"
end
def valid_attributes(attributes={})
{ :email => generate_unique_email,
:password => '123456',
:password_confirmation => '123456' }.update(attributes)
end
def new_user(attributes={})
User.new(valid_attributes(attributes))
end
def create_user(attributes={})
User.create!(valid_attributes(attributes))
end
def field_accessible?(field)
new_user(field => 'test').send(field) == 'test'
end
end

243
test/rails_app/README Normal file
View file

@ -0,0 +1,243 @@
== Welcome to Rails
Rails is a web-application framework that includes everything needed to create
database-backed web applications according to the Model-View-Control pattern.
This pattern splits the view (also called the presentation) into "dumb" templates
that are primarily responsible for inserting pre-built data in between HTML tags.
The model contains the "smart" domain objects (such as Account, Product, Person,
Post) that holds all the business logic and knows how to persist themselves to
a database. The controller handles the incoming requests (such as Save New Account,
Update Product, Show Post) by manipulating the model and directing data to the view.
In Rails, the model is handled by what's called an object-relational mapping
layer entitled Active Record. This layer allows you to present the data from
database rows as objects and embellish these data objects with business logic
methods. You can read more about Active Record in
link:files/vendor/rails/activerecord/README.html.
The controller and view are handled by the Action Pack, which handles both
layers by its two parts: Action View and Action Controller. These two layers
are bundled in a single package due to their heavy interdependence. This is
unlike the relationship between the Active Record and Action Pack that is much
more separate. Each of these packages can be used independently outside of
Rails. You can read more about Action Pack in
link:files/vendor/rails/actionpack/README.html.
== Getting Started
1. At the command prompt, start a new Rails application using the <tt>rails</tt> command
and your application name. Ex: rails myapp
2. Change directory into myapp and start the web server: <tt>script/server</tt> (run with --help for options)
3. Go to http://localhost:3000/ and get "Welcome aboard: You're riding the Rails!"
4. Follow the guidelines to start developing your application
== Web Servers
By default, Rails will try to use Mongrel if it's are installed when started with script/server, otherwise Rails will use WEBrick, the webserver that ships with Ruby. But you can also use Rails
with a variety of other web servers.
Mongrel is a Ruby-based webserver with a C component (which requires compilation) that is
suitable for development and deployment of Rails applications. If you have Ruby Gems installed,
getting up and running with mongrel is as easy as: <tt>gem install mongrel</tt>.
More info at: http://mongrel.rubyforge.org
Say other Ruby web servers like Thin and Ebb or regular web servers like Apache or LiteSpeed or
Lighttpd or IIS. The Ruby web servers are run through Rack and the latter can either be setup to use
FCGI or proxy to a pack of Mongrels/Thin/Ebb servers.
== Apache .htaccess example for FCGI/CGI
# General Apache options
AddHandler fastcgi-script .fcgi
AddHandler cgi-script .cgi
Options +FollowSymLinks +ExecCGI
# If you don't want Rails to look in certain directories,
# use the following rewrite rules so that Apache won't rewrite certain requests
#
# Example:
# RewriteCond %{REQUEST_URI} ^/notrails.*
# RewriteRule .* - [L]
# Redirect all requests not available on the filesystem to Rails
# By default the cgi dispatcher is used which is very slow
#
# For better performance replace the dispatcher with the fastcgi one
#
# Example:
# RewriteRule ^(.*)$ dispatch.fcgi [QSA,L]
RewriteEngine On
# If your Rails application is accessed via an Alias directive,
# then you MUST also set the RewriteBase in this htaccess file.
#
# Example:
# Alias /myrailsapp /path/to/myrailsapp/public
# RewriteBase /myrailsapp
RewriteRule ^$ index.html [QSA]
RewriteRule ^([^.]+)$ $1.html [QSA]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ dispatch.cgi [QSA,L]
# In case Rails experiences terminal errors
# Instead of displaying this message you can supply a file here which will be rendered instead
#
# Example:
# ErrorDocument 500 /500.html
ErrorDocument 500 "<h2>Application error</h2>Rails application failed to start properly"
== Debugging Rails
Sometimes your application goes wrong. Fortunately there are a lot of tools that
will help you debug it and get it back on the rails.
First area to check is the application log files. Have "tail -f" commands running
on the server.log and development.log. Rails will automatically display debugging
and runtime information to these files. Debugging info will also be shown in the
browser on requests from 127.0.0.1.
You can also log your own messages directly into the log file from your code using
the Ruby logger class from inside your controllers. Example:
class WeblogController < ActionController::Base
def destroy
@weblog = Weblog.find(params[:id])
@weblog.destroy
logger.info("#{Time.now} Destroyed Weblog ID ##{@weblog.id}!")
end
end
The result will be a message in your log file along the lines of:
Mon Oct 08 14:22:29 +1000 2007 Destroyed Weblog ID #1
More information on how to use the logger is at http://www.ruby-doc.org/core/
Also, Ruby documentation can be found at http://www.ruby-lang.org/ including:
* The Learning Ruby (Pickaxe) Book: http://www.ruby-doc.org/docs/ProgrammingRuby/
* Learn to Program: http://pine.fm/LearnToProgram/ (a beginners guide)
These two online (and free) books will bring you up to speed on the Ruby language
and also on programming in general.
== Debugger
Debugger support is available through the debugger command when you start your Mongrel or
Webrick server with --debugger. This means that you can break out of execution at any point
in the code, investigate and change the model, AND then resume execution!
You need to install ruby-debug to run the server in debugging mode. With gems, use 'gem install ruby-debug'
Example:
class WeblogController < ActionController::Base
def index
@posts = Post.find(:all)
debugger
end
end
So the controller will accept the action, run the first line, then present you
with a IRB prompt in the server window. Here you can do things like:
>> @posts.inspect
=> "[#<Post:0x14a6be8 @attributes={\"title\"=>nil, \"body\"=>nil, \"id\"=>\"1\"}>,
#<Post:0x14a6620 @attributes={\"title\"=>\"Rails you know!\", \"body\"=>\"Only ten..\", \"id\"=>\"2\"}>]"
>> @posts.first.title = "hello from a debugger"
=> "hello from a debugger"
...and even better is that you can examine how your runtime objects actually work:
>> f = @posts.first
=> #<Post:0x13630c4 @attributes={"title"=>nil, "body"=>nil, "id"=>"1"}>
>> f.
Display all 152 possibilities? (y or n)
Finally, when you're ready to resume execution, you enter "cont"
== Console
You can interact with the domain model by starting the console through <tt>script/console</tt>.
Here you'll have all parts of the application configured, just like it is when the
application is running. You can inspect domain models, change values, and save to the
database. Starting the script without arguments will launch it in the development environment.
Passing an argument will specify a different environment, like <tt>script/console production</tt>.
To reload your controllers and models after launching the console run <tt>reload!</tt>
== dbconsole
You can go to the command line of your database directly through <tt>script/dbconsole</tt>.
You would be connected to the database with the credentials defined in database.yml.
Starting the script without arguments will connect you to the development database. Passing an
argument will connect you to a different database, like <tt>script/dbconsole production</tt>.
Currently works for mysql, postgresql and sqlite.
== Description of Contents
app
Holds all the code that's specific to this particular application.
app/controllers
Holds controllers that should be named like weblogs_controller.rb for
automated URL mapping. All controllers should descend from ApplicationController
which itself descends from ActionController::Base.
app/models
Holds models that should be named like post.rb.
Most models will descend from ActiveRecord::Base.
app/views
Holds the template files for the view that should be named like
weblogs/index.html.erb for the WeblogsController#index action. All views use eRuby
syntax.
app/views/layouts
Holds the template files for layouts to be used with views. This models the common
header/footer method of wrapping views. In your views, define a layout using the
<tt>layout :default</tt> and create a file named default.html.erb. Inside default.html.erb,
call <% yield %> to render the view using this layout.
app/helpers
Holds view helpers that should be named like weblogs_helper.rb. These are generated
for you automatically when using script/generate for controllers. Helpers can be used to
wrap functionality for your views into methods.
config
Configuration files for the Rails environment, the routing map, the database, and other dependencies.
db
Contains the database schema in schema.rb. db/migrate contains all
the sequence of Migrations for your schema.
doc
This directory is where your application documentation will be stored when generated
using <tt>rake doc:app</tt>
lib
Application specific libraries. Basically, any kind of custom code that doesn't
belong under controllers, models, or helpers. This directory is in the load path.
public
The directory available for the web server. Contains subdirectories for images, stylesheets,
and javascripts. Also contains the dispatchers and the default HTML files. This should be
set as the DOCUMENT_ROOT of your web server.
script
Helper scripts for automation and generation.
test
Unit and functional tests along with fixtures. When using the script/generate scripts, template
test files will be generated for you and placed in this directory.
vendor
External libraries that the application depends on. Also includes the plugins subdirectory.
If the app has frozen rails, those gems also go here, under vendor/rails/.
This directory is in the load path.

10
test/rails_app/Rakefile Normal file
View file

@ -0,0 +1,10 @@
# Add your own tasks in files placed in lib/tasks ending in .rake,
# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
require(File.join(File.dirname(__FILE__), 'config', 'boot'))
require 'rake'
require 'rake/testtask'
require 'rake/rdoctask'
require 'tasks/rails'

View file

@ -0,0 +1,10 @@
# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.
class ApplicationController < ActionController::Base
helper :all # include all helpers, all the time
protect_from_forgery # See ActionController::RequestForgeryProtection for details
# Scrub sensitive parameters from your log
# filter_parameter_logging :password
end

View file

@ -0,0 +1,6 @@
class HomeController < ApplicationController
before_filter :authenticate!
def index
end
end

View file

@ -0,0 +1,3 @@
# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
end

View file

@ -0,0 +1,6 @@
class User < ActiveRecord::Base
include Devise::Authenticable
include Devise::Confirmable
include Devise::Recoverable
include Devise::Validatable
end

View file

@ -0,0 +1 @@
Hello World!

View file

@ -0,0 +1,16 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Devise Test App</title>
</head>
<body>
<div id="container">
<%- flash.each do |name, msg| -%>
<%= content_tag :div, msg, :id => "flash_#{name}" %>
<%- end -%>
<%= yield %>
</div>
</body>
</html>

View file

@ -0,0 +1,110 @@
# Don't change this file!
# Configure your app in config/environment.rb and config/environments/*.rb
RAILS_ROOT = "#{File.dirname(__FILE__)}/.." unless defined?(RAILS_ROOT)
module Rails
class << self
def boot!
unless booted?
preinitialize
pick_boot.run
end
end
def booted?
defined? Rails::Initializer
end
def pick_boot
(vendor_rails? ? VendorBoot : GemBoot).new
end
def vendor_rails?
File.exist?("#{RAILS_ROOT}/vendor/rails")
end
def preinitialize
load(preinitializer_path) if File.exist?(preinitializer_path)
end
def preinitializer_path
"#{RAILS_ROOT}/config/preinitializer.rb"
end
end
class Boot
def run
load_initializer
Rails::Initializer.run(:set_load_path)
end
end
class VendorBoot < Boot
def load_initializer
require "#{RAILS_ROOT}/vendor/rails/railties/lib/initializer"
Rails::Initializer.run(:install_gem_spec_stubs)
Rails::GemDependency.add_frozen_gem_path
end
end
class GemBoot < Boot
def load_initializer
self.class.load_rubygems
load_rails_gem
require 'initializer'
end
def load_rails_gem
if version = self.class.gem_version
gem 'rails', version
else
gem 'rails'
end
rescue Gem::LoadError => load_error
$stderr.puts %(Missing the Rails #{version} gem. Please `gem install -v=#{version} rails`, update your RAILS_GEM_VERSION setting in config/environment.rb for the Rails version you do have installed, or comment out RAILS_GEM_VERSION to use the latest version installed.)
exit 1
end
class << self
def rubygems_version
Gem::RubyGemsVersion rescue nil
end
def gem_version
if defined? RAILS_GEM_VERSION
RAILS_GEM_VERSION
elsif ENV.include?('RAILS_GEM_VERSION')
ENV['RAILS_GEM_VERSION']
else
parse_gem_version(read_environment_rb)
end
end
def load_rubygems
min_version = '1.3.2'
require 'rubygems'
unless rubygems_version >= min_version
$stderr.puts %Q(Rails requires RubyGems >= #{min_version} (you have #{rubygems_version}). Please `gem update --system` and try again.)
exit 1
end
rescue LoadError
$stderr.puts %Q(Rails requires RubyGems >= #{min_version}. Please install RubyGems and try again: http://rubygems.rubyforge.org)
exit 1
end
def parse_gem_version(text)
$1 if text =~ /^[^#]*RAILS_GEM_VERSION\s*=\s*["']([!~<>=]*\s*[\d.]+)["']/
end
private
def read_environment_rb
File.read("#{RAILS_ROOT}/config/environment.rb")
end
end
end
end
# All that for this:
Rails.boot!

View file

@ -0,0 +1,18 @@
development:
adapter: sqlite3
database: db/development.sqlite3
pool: 5
timeout: 5000
test:
adapter: sqlite3
database: db/test.sqlite3
pool: 5
timeout: 5000
production:
adapter: sqlite3
database: db/production.sqlite3
pool: 5
timeout: 5000

View file

@ -0,0 +1,41 @@
# Be sure to restart your server when you modify this file
# Specifies gem version of Rails to use when vendor/rails is not present
RAILS_GEM_VERSION = '2.3.4' unless defined? RAILS_GEM_VERSION
# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')
Rails::Initializer.run do |config|
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Add additional load paths for your own custom dirs
# config.load_paths += %W( #{RAILS_ROOT}/extras )
# Specify gems that this application depends on and have them installed with rake gems:install
# config.gem "bj"
# config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net"
# config.gem "sqlite3-ruby", :lib => "sqlite3"
# config.gem "aws-s3", :lib => "aws/s3"
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Skip frameworks you're not going to use. To use Rails without a database,
# you must remove the Active Record framework.
# config.frameworks -= [ :active_record, :active_resource, :action_mailer ]
# Activate observers that should always be running
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names.
config.time_zone = 'UTC'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')]
# config.i18n.default_locale = :de
end

View file

@ -0,0 +1,17 @@
# Settings specified here will take precedence over those in config/environment.rb
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the webserver when you make code changes.
config.cache_classes = false
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true
# Show full error reports and disable caching
config.action_controller.consider_all_requests_local = true
config.action_view.debug_rjs = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send
config.action_mailer.raise_delivery_errors = false

View file

@ -0,0 +1,28 @@
# Settings specified here will take precedence over those in config/environment.rb
# The production environment is meant for finished, "live" apps.
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.action_controller.consider_all_requests_local = false
config.action_controller.perform_caching = true
config.action_view.cache_template_loading = true
# See everything in the log (default is :info)
# config.log_level = :debug
# Use a different logger for distributed setups
# config.logger = SyslogLogger.new
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and javascripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
# Enable threaded mode
# config.threadsafe!

View file

@ -0,0 +1,28 @@
# Settings specified here will take precedence over those in config/environment.rb
# The test environment is used exclusively to run your application's
# test suite. You never need to work with it otherwise. Remember that
# your test database is "scratch space" for the test suite and is wiped
# and recreated between test runs. Don't rely on the data there!
config.cache_classes = true
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true
# Show full error reports and disable caching
config.action_controller.consider_all_requests_local = true
config.action_controller.perform_caching = false
config.action_view.cache_template_loading = true
# Disable request forgery protection in test environment
config.action_controller.allow_forgery_protection = false
# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
config.action_mailer.delivery_method = :test
# Use SQL instead of Active Record's schema dumper when creating the test database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
# config.active_record.schema_format = :sql

View file

@ -0,0 +1,7 @@
# Be sure to restart your server when you modify this file.
# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces.
# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }
# You can also remove all the silencers if you're trying do debug a problem that might steem from framework code.
# Rails.backtrace_cleaner.remove_silencers!

View file

@ -0,0 +1,10 @@
# Be sure to restart your server when you modify this file.
# Add new inflection rules using the following format
# (all these examples are active by default):
# ActiveSupport::Inflector.inflections do |inflect|
# inflect.plural /^(ox)$/i, '\1en'
# inflect.singular /^(ox)en/i, '\1'
# inflect.irregular 'person', 'people'
# inflect.uncountable %w( fish sheep )
# end

View file

@ -0,0 +1,5 @@
# Be sure to restart your server when you modify this file.
# Add new mime types for use in respond_to blocks:
# Mime::Type.register "text/richtext", :rtf
# Mime::Type.register_alias "text/html", :iphone

View file

@ -0,0 +1,21 @@
# Be sure to restart your server when you modify this file.
# These settings change the behavior of Rails 2 apps and will be defaults
# for Rails 3. You can remove this initializer when Rails 3 is released.
if defined?(ActiveRecord)
# Include Active Record class name as root for JSON serialized output.
ActiveRecord::Base.include_root_in_json = true
# Store the full class name (including module namespace) in STI type column.
ActiveRecord::Base.store_full_sti_class = true
end
ActionController::Routing.generate_best_match = false
# Use ISO 8601 format for JSON serialized times and dates.
ActiveSupport.use_standard_json_time_format = true
# Don't escape HTML entities in JSON, leave that for the #json_escape helper.
# if you're including raw json in an HTML page.
ActiveSupport.escape_html_entities_in_json = false

View file

@ -0,0 +1,15 @@
# Be sure to restart your server when you modify this file.
# Your secret key for verifying cookie session data integrity.
# If you change this key, all old sessions will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
ActionController::Base.session = {
:key => '_rails_app_session',
:secret => '89e8147901a0d7c221ac130e0ded3eeab6dab4a97127255909f08fedaae371918b41dec9d4d75c5b27a55c3772d43c2b6a3cbac232c5cc2ce4b8ec22242f5e60'
}
# Use the database for sessions instead of the cookie-based default,
# which shouldn't be used to store highly confidential information
# (create the session table with "rake db:sessions:create")
# ActionController::Base.session_store = :active_record_store

View file

@ -0,0 +1,5 @@
# Sample localization file for English. Add more files in this directory for other locales.
# See http://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points.
en:
hello: "Hello world"

View file

@ -0,0 +1,4 @@
ActionController::Routing::Routes.draw do |map|
map.resources :home, :only => :index
map.root :controller => :home
end

View file

@ -0,0 +1,7 @@
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ :name => 'Chicago' }, { :name => 'Copenhagen' }])
# Major.create(:name => 'Daley', :city => cities.first)

View file

@ -0,0 +1 @@
# Logfile created on Wed Oct 07 20:20:37 -0300 2009

26288
test/rails_app/log/test.log Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,30 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>The page you were looking for doesn't exist (404)</title>
<style type="text/css">
body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }
div.dialog {
width: 25em;
padding: 0 4em;
margin: 4em auto 0 auto;
border: 1px solid #ccc;
border-right-color: #999;
border-bottom-color: #999;
}
h1 { font-size: 100%; color: #f00; line-height: 1.5em; }
</style>
</head>
<body>
<!-- This file lives in public/404.html -->
<div class="dialog">
<h1>The page you were looking for doesn't exist.</h1>
<p>You may have mistyped the address or the page may have moved.</p>
</div>
</body>
</html>

View file

@ -0,0 +1,30 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>The change you wanted was rejected (422)</title>
<style type="text/css">
body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }
div.dialog {
width: 25em;
padding: 0 4em;
margin: 4em auto 0 auto;
border: 1px solid #ccc;
border-right-color: #999;
border-bottom-color: #999;
}
h1 { font-size: 100%; color: #f00; line-height: 1.5em; }
</style>
</head>
<body>
<!-- This file lives in public/422.html -->
<div class="dialog">
<h1>The change you wanted was rejected.</h1>
<p>Maybe you tried to change something you didn't have access to.</p>
</div>
</body>
</html>

View file

@ -0,0 +1,30 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>We're sorry, but something went wrong (500)</title>
<style type="text/css">
body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }
div.dialog {
width: 25em;
padding: 0 4em;
margin: 4em auto 0 auto;
border: 1px solid #ccc;
border-right-color: #999;
border-bottom-color: #999;
}
h1 { font-size: 100%; color: #f00; line-height: 1.5em; }
</style>
</head>
<body>
<!-- This file lives in public/500.html -->
<div class="dialog">
<h1>We're sorry, but something went wrong.</h1>
<p>We've been notified about this issue and we'll take a look at it shortly.</p>
</div>
</body>
</html>

View file

4
test/rails_app/script/about Executable file
View file

@ -0,0 +1,4 @@
#!/usr/bin/env ruby
require File.expand_path('../../config/boot', __FILE__)
$LOAD_PATH.unshift "#{RAILTIES_PATH}/builtin/rails_info"
require 'commands/about'

3
test/rails_app/script/console Executable file
View file

@ -0,0 +1,3 @@
#!/usr/bin/env ruby
require File.expand_path('../../config/boot', __FILE__)
require 'commands/console'

View file

@ -0,0 +1,3 @@
#!/usr/bin/env ruby
require File.expand_path('../../config/boot', __FILE__)
require 'commands/dbconsole'

3
test/rails_app/script/destroy Executable file
View file

@ -0,0 +1,3 @@
#!/usr/bin/env ruby
require File.expand_path('../../config/boot', __FILE__)
require 'commands/destroy'

3
test/rails_app/script/generate Executable file
View file

@ -0,0 +1,3 @@
#!/usr/bin/env ruby
require File.expand_path('../../config/boot', __FILE__)
require 'commands/generate'

View file

@ -0,0 +1,3 @@
#!/usr/bin/env ruby
require File.expand_path('../../../config/boot', __FILE__)
require 'commands/performance/benchmarker'

View file

@ -0,0 +1,3 @@
#!/usr/bin/env ruby
require File.expand_path('../../../config/boot', __FILE__)
require 'commands/performance/profiler'

3
test/rails_app/script/plugin Executable file
View file

@ -0,0 +1,3 @@
#!/usr/bin/env ruby
require File.expand_path('../../config/boot', __FILE__)
require 'commands/plugin'

3
test/rails_app/script/runner Executable file
View file

@ -0,0 +1,3 @@
#!/usr/bin/env ruby
require File.expand_path('../../config/boot', __FILE__)
require 'commands/runner'

3
test/rails_app/script/server Executable file
View file

@ -0,0 +1,3 @@
#!/usr/bin/env ruby
require File.expand_path('../../config/boot', __FILE__)
require 'commands/server'

View file

@ -0,0 +1,7 @@
# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
# one:
# column: value
#
# two:
# column: value

View file

@ -0,0 +1,8 @@
require 'test_helper'
class UserTest < ActiveSupport::TestCase
# Replace this with your real tests.
test "the truth" do
assert true
end
end

1
test/rails_app/vendor/plugins/devise vendored Symbolic link
View file

@ -0,0 +1 @@
../../../../

View file

@ -1,12 +1,17 @@
RAILS_ENV = ENV["RAILS_ENV"] = "test"
require 'test/unit'
require 'rubygems'
require 'active_support'
require 'active_support/test_case'
require 'action_mailer'
require 'active_record'
require File.join(File.dirname(__FILE__), 'rails_app', 'config', 'environment')
require File.join(File.dirname(__FILE__), '..', 'lib', 'devise')
require 'test_help'
require 'webrat'
require 'assertions_helper'
require 'models_helper'
require 'integration_tests_helper'
require 'model_builder'
ActiveSupport::Dependencies.load_paths << File.expand_path(File.dirname(__FILE__) + '/../lib')
require_dependency 'devise'
ActionMailer::Base.delivery_method = :test
ActionMailer::Base.perform_deliveries = true
@ -24,60 +29,11 @@ ActiveRecord::Schema.define(:version => 1) do
end
end
class User < ::ActiveRecord::Base
include ::Devise::Authenticable
Webrat.configure do |config|
config.mode = :rails
end
class ActiveSupport::TestCase
def assert_not(assertion)
assert !assertion
end
def assert_blank(assertion)
assert assertion.blank?
end
def assert_not_blank(assertion)
assert !assertion.blank?
end
alias :assert_present :assert_not_blank
def assert_email_sent(&block)
assert_difference('ActionMailer::Base.deliveries.size') { yield }
end
def assert_email_not_sent(&block)
assert_no_difference('ActionMailer::Base.deliveries.size') { yield }
end
def setup_mailer
ActionMailer::Base.deliveries = []
end
# Helpers for creating new users
#
def generate_unique_email
@@email_count ||= 0
@@email_count += 1
"test#{@@email_count}@email.com"
end
def valid_attributes(attributes={})
{ :email => generate_unique_email,
:password => '123456',
:password_confirmation => '123456' }.update(attributes)
end
def new_user(attributes={})
User.new(valid_attributes(attributes))
end
def create_user(attributes={})
User.create!(valid_attributes(attributes))
end
def field_accessible?(field)
new_user(field => 'test').send(field) == 'test'
end
self.use_transactional_fixtures = true
self.use_instantiated_fixtures = false
end