Permalink
Browse files

Finish sign in

End of chapter 8 + cucumber
  • Loading branch information...
1 parent 58c7c5d commit 4871614f6a043772bc148e06eaed38d1d21343e3 @simonewebdesign committed Dec 27, 2012
@@ -12,4 +12,5 @@
//
//= require jquery
//= require jquery_ujs
+//= require bootstrap
//= require_tree .
@@ -0,0 +1,3 @@
+# Place all the behaviors and hooks related to the matching controller here.
+# All this logic will automatically be available in application.js.
+# You can use CoffeeScript in this file: http://jashkenas.github.com/coffee-script/
@@ -0,0 +1,3 @@
+// Place all the styles related to the sessions controller here.
+// They will automatically be included in application.css.
+// You can use Sass (SCSS) here: http://sass-lang.com/
@@ -1,3 +1,4 @@
class ApplicationController < ActionController::Base
protect_from_forgery
+ include SessionsHelper
end
@@ -0,0 +1,21 @@
+class SessionsController < ApplicationController
+
+ def new
+ end
+
+ def create
+ user = User.find_by_email(params[:session][:email].downcase)
+ if user && user.authenticate(params[:session][:password])
+ sign_in user
+ redirect_to user
+ else
+ flash.now[:error] = 'Invalid email/password combination'
+ render 'new'
+ end
+ end
+
+ def destroy
+ sign_out
+ redirect_to root_url
+ end
+end
@@ -12,6 +12,7 @@ def create
@user = User.new(params[:user])
if @user.save
# Handle a successful save.
+ sign_in @user
# render "users/#{@user}"
flash[:success] = "Welcome to the Sample App!"
redirect_to @user
@@ -0,0 +1,25 @@
+module SessionsHelper
+
+ def sign_in(user)
+ cookies.permanent[:remember_token] = user.remember_token
+ self.current_user = user
+ end
+
+ def signed_in?
+ !current_user.nil?
+ end
+
+ def sign_out
+ self.current_user = nil
+ cookies.delete(:remember_token)
+ end
+
+ def current_user=(user)
+ @current_user = user
+ end
+
+ def current_user
+ @current_user ||= User.find_by_remember_token(cookies[:remember_token])
+ end
+
+end
View
@@ -21,4 +21,11 @@ class User < ActiveRecord::Base
validates :password_confirmation, presence: true
before_save { |user| user.email = email.downcase }
+ before_save :create_remember_token
+
+ private
+
+ def create_remember_token
+ self.remember_token = SecureRandom.urlsafe_base64
+ end
end
@@ -4,9 +4,26 @@
<%= link_to "sample app", root_path, id: "logo" %>
<nav>
<ul class="nav pull-right">
- <li><%= link_to "Home", root_path %></li>
- <li><%= link_to "Help", help_path %></li>
- <li><%= link_to "Sign in", '#' %></li>
+ <li><%= link_to "Home", root_path %></li>
+ <li><%= link_to "Help", help_path %></li>
+ <% if signed_in? %>
+ <li><%= link_to "Users", '#' %></li>
+ <li id="fat-menu" class="dropdown">
+ <a href="#" class="dropdown-toggle" data-toggle="dropdown">
+ Account <b class="caret"></b>
+ </a>
+ <ul class="dropdown-menu">
+ <li><%= link_to "Profile", current_user %></li>
+ <li><%= link_to "Settings", '#' %></li>
+ <li class="divider"></li>
+ <li>
+ <%= link_to "Sign out", signout_path, method: "delete" %>
+ </li>
+ </ul>
+ </li>
+ <% else %>
+ <li><%= link_to "Sign in", signin_path %></li>
+ <% end %>
</ul>
</nav>
</div>
@@ -0,0 +1,19 @@
+<% provide(:title, "Sign in") %>
+<h1>Sign in</h1>
+
+<div class="row">
+ <div class="span6 offset3">
+ <%= form_for(:session, url: sessions_path) do |f| %>
+
+ <%= f.label :email %>
+ <%= f.text_field :email %>
+
+ <%= f.label :password %>
+ <%= f.password_field :password %>
+
+ <%= f.submit "Sign in", class: "btn btn-large btn-primary" %>
+ <% end %>
+
+ <p>New user? <%= link_to "Sign up now!", signup_path %></p>
+ </div>
+</div>
View
@@ -0,0 +1,8 @@
+<%
+rerun = File.file?('rerun.txt') ? IO.read('rerun.txt') : ""
+rerun_opts = rerun.to_s.strip.empty? ? "--format #{ENV['CUCUMBER_FORMAT'] || 'progress'} features" : "--format #{ENV['CUCUMBER_FORMAT'] || 'pretty'} #{rerun}"
+std_opts = "--format #{ENV['CUCUMBER_FORMAT'] || 'pretty'} --strict --tags ~@wip"
+%>
+default: <%= std_opts %> features
+wip: --tags @wip:3 --wip features
+rerun: <%= rerun_opts %> --format rerun --out rerun.txt --strict --tags ~@wip
View
@@ -3,7 +3,9 @@ development:
database: sample_app_dev
host: localhost
-test:
+test: &test
adapter: postgresql
database: sample_app_test
- host: localhost
+ host: localhost
+cucumber:
+ <<: *test
View
@@ -1,16 +1,21 @@
SampleApp::Application.routes.draw do
resources :users
-
-# get "users/new"
+ resources :sessions, only: [:new, :create, :destroy]
root to: 'static_pages#home'
- match '/signup' => 'users#new'
+ # get "users/new"
+ match '/signup' => 'users#new' # register
+ # static pages
match '/help' => 'static_pages#help'
match '/about' => 'static_pages#about'
match '/contact' => 'static_pages#contact'
+ # sessions
+ match '/signin', to: 'sessions#new' # login
+ match '/signout', to: 'sessions#destroy', via: :delete # logout
+
# The priority is based upon order of creation:
# first created -> highest priority.
@@ -0,0 +1,6 @@
+class AddRememberTokenToUsers < ActiveRecord::Migration
+ def change
+ add_column :users, :remember_token, :string
+ add_index :users, :remember_token
+ end
+end
View
@@ -11,16 +11,18 @@
#
# It's strongly recommended to check this file into your version control system.
-ActiveRecord::Schema.define(:version => 20121218220440) do
+ActiveRecord::Schema.define(:version => 20121222171319) do
create_table "users", :force => true do |t|
t.string "name"
t.string "email"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.string "password_digest"
+ t.string "remember_token"
end
add_index "users", ["email"], :name => "index_users_on_email", :unique => true
+ add_index "users", ["remember_token"], :name => "index_users_on_remember_token"
end
@@ -0,0 +1,13 @@
+Feature: Signing in
+
+ Scenario: Unsuccessful signin
+ Given a user visits the signin page
+ When he submits invalid signin information
+ Then he should see an error message
+
+ Scenario: Successful signin
+ Given a user visits the signin page
+ And the user has an account
+ And the user submits valid signin information
+ Then he should see his profile page
+ And he should see a signout link
@@ -0,0 +1,30 @@
+Given /^a user visits the signin page$/ do
+ visit signin_path
+end
+
+When /^he submits invalid signin information$/ do
+ click_button "Sign in"
+end
+
+Then /^he should see an error message$/ do
+ page.should have_selector('div.alert.alert-error')
+end
+
+Given /^the user has an account$/ do
+ @user = User.create(name: "Example User", email: "user@example.com",
+ password: "foobar", password_confirmation: "foobar")
+end
+
+When /^the user submits valid signin information$/ do
+ fill_in "Email", with: @user.email
+ fill_in "Password", with: @user.password
+ click_button "Sign in"
+end
+
+Then /^he should see his profile page$/ do
+ page.should have_selector('title', text: @user.name)
+end
+
+Then /^he should see a signout link$/ do
+ page.should have_link('Sign out', href: signout_path)
+end
View
@@ -0,0 +1,56 @@
+# IMPORTANT: This file is generated by cucumber-rails - edit at your own peril.
+# It is recommended to regenerate this file in the future when you upgrade to a
+# newer version of cucumber-rails. Consider adding your own code to a new file
+# instead of editing this one. Cucumber will automatically load all features/**/*.rb
+# files.
+
+require 'cucumber/rails'
+
+# Capybara defaults to XPath selectors rather than Webrat's default of CSS3. In
+# order to ease the transition to Capybara we set the default here. If you'd
+# prefer to use XPath just remove this line and adjust any selectors in your
+# steps to use the XPath syntax.
+Capybara.default_selector = :css
+
+# By default, any exception happening in your Rails application will bubble up
+# to Cucumber so that your scenario will fail. This is a different from how
+# your application behaves in the production environment, where an error page will
+# be rendered instead.
+#
+# Sometimes we want to override this default behaviour and allow Rails to rescue
+# exceptions and display an error page (just like when the app is running in production).
+# Typical scenarios where you want to do this is when you test your error pages.
+# There are two ways to allow Rails to rescue exceptions:
+#
+# 1) Tag your scenario (or feature) with @allow-rescue
+#
+# 2) Set the value below to true. Beware that doing this globally is not
+# recommended as it will mask a lot of errors for you!
+#
+ActionController::Base.allow_rescue = false
+
+# Remove/comment out the lines below if your app doesn't have a database.
+# For some databases (like MongoDB and CouchDB) you may need to use :truncation instead.
+begin
+ DatabaseCleaner.strategy = :transaction
+rescue NameError
+ raise "You need to add database_cleaner to your Gemfile (in the :test group) if you wish to use it."
+end
+
+# You may also want to configure DatabaseCleaner to use different strategies for certain features and scenarios.
+# See the DatabaseCleaner documentation for details. Example:
+#
+# Before('@no-txn,@selenium,@culerity,@celerity,@javascript') do
+# DatabaseCleaner.strategy = :truncation, {:except => %w[widgets]}
+# end
+#
+# Before('~@no-txn', '~@selenium', '~@culerity', '~@celerity', '~@javascript') do
+# DatabaseCleaner.strategy = :transaction
+# end
+#
+
+# Possible values are :truncation and :transaction
+# The :transaction strategy is faster, but might give you threading problems.
+# See https://github.com/cucumber/cucumber-rails/blob/master/features/choose_javascript_database_strategy.feature
+Cucumber::Rails::Database.javascript_strategy = :truncation
+
View
@@ -0,0 +1,65 @@
+# IMPORTANT: This file is generated by cucumber-rails - edit at your own peril.
+# It is recommended to regenerate this file in the future when you upgrade to a
+# newer version of cucumber-rails. Consider adding your own code to a new file
+# instead of editing this one. Cucumber will automatically load all features/**/*.rb
+# files.
+
+
+unless ARGV.any? {|a| a =~ /^gems/} # Don't load anything when running the gems:* tasks
+
+vendored_cucumber_bin = Dir["#{Rails.root}/vendor/{gems,plugins}/cucumber*/bin/cucumber"].first
+$LOAD_PATH.unshift(File.dirname(vendored_cucumber_bin) + '/../lib') unless vendored_cucumber_bin.nil?
+
+begin
+ require 'cucumber/rake/task'
+
+ namespace :cucumber do
+ Cucumber::Rake::Task.new({:ok => 'db:test:prepare'}, 'Run features that should pass') do |t|
+ t.binary = vendored_cucumber_bin # If nil, the gem's binary is used.
+ t.fork = true # You may get faster startup if you set this to false
+ t.profile = 'default'
+ end
+
+ Cucumber::Rake::Task.new({:wip => 'db:test:prepare'}, 'Run features that are being worked on') do |t|
+ t.binary = vendored_cucumber_bin
+ t.fork = true # You may get faster startup if you set this to false
+ t.profile = 'wip'
+ end
+
+ Cucumber::Rake::Task.new({:rerun => 'db:test:prepare'}, 'Record failing features and run only them if any exist') do |t|
+ t.binary = vendored_cucumber_bin
+ t.fork = true # You may get faster startup if you set this to false
+ t.profile = 'rerun'
+ end
+
+ desc 'Run all features'
+ task :all => [:ok, :wip]
+
+ task :statsetup do
+ require 'rails/code_statistics'
+ ::STATS_DIRECTORIES << %w(Cucumber\ features features) if File.exist?('features')
+ ::CodeStatistics::TEST_TYPES << "Cucumber features" if File.exist?('features')
+ end
+ end
+ desc 'Alias for cucumber:ok'
+ task :cucumber => 'cucumber:ok'
+
+ task :default => :cucumber
+
+ task :features => :cucumber do
+ STDERR.puts "*** The 'features' task is deprecated. See rake -T cucumber ***"
+ end
+
+ # In case we don't have ActiveRecord, append a no-op task that we can depend upon.
+ task 'db:test:prepare' do
+ end
+
+ task :stats => 'cucumber:statsetup'
+rescue LoadError
+ desc 'cucumber rake task not available (cucumber not installed)'
+ task :cucumber do
+ abort 'Cucumber rake task is not available. Be sure to install cucumber as a gem or plugin'
+ end
+end
+
+end
View
@@ -0,0 +1,10 @@
+#!/usr/bin/env ruby
+
+vendored_cucumber_bin = Dir["#{File.dirname(__FILE__)}/../vendor/{gems,plugins}/cucumber*/bin/cucumber"].first
+if vendored_cucumber_bin
+ load File.expand_path(vendored_cucumber_bin)
+else
+ require 'rubygems' unless ENV['NO_RUBYGEMS']
+ require 'cucumber'
+ load Cucumber::BINARY
+end
Oops, something went wrong.

0 comments on commit 4871614

Please sign in to comment.