Commit cda9d573

mo khan <mo@mokhan.ca>
2014-09-18 03:20:14
add email validation.
1 parent cf41732
Changed files (4)
app/controllers/registrations_controller.rb
@@ -0,0 +1,17 @@
+class RegistrationsController < ApplicationController
+  def create
+    user = User.create(secure_params)
+    if user.save
+      redirect_to my_root_path
+    else
+      flash[:error] = user.errors.full_messages
+      redirect_to new_session_path
+    end
+  end
+
+  private
+
+  def secure_params
+    params.require(:user).permit(:name, :email, :password)
+  end
+end
app/models/user.rb
@@ -1,11 +1,20 @@
 require 'bcrypt'
 
+class EmailValidator < ActiveModel::EachValidator
+  def validate_each(record, attribute, value)
+    unless value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
+      record.errors[attribute] << (options[:message] || "is not an email")
+    end
+  end
+end
+
 class User < ActiveRecord::Base
   include BCrypt
   before_save :ensure_authentication_token
   after_create :send_welcome_email unless Rails.env.test?
 
   validates :name,  :presence => true
+  validates :email, presence: true, uniqueness: true, email: true
   validates :website, :format => URI::regexp(%w(http https)), :allow_blank => true
   #devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :token_authenticatable
 
@@ -118,4 +127,5 @@ class User < ActiveRecord::Base
   def ensure_authentication_token
     self.authentication_token = SecureRandom.hex(32) if self.authentication_token.blank?
   end
+
 end
spec/controllers/registrations_controller_spec.rb
@@ -0,0 +1,18 @@
+require 'rails_helper'
+
+describe RegistrationsController do
+  describe "#create" do
+    it 'creates a new user' do
+      post :create, user: { name: 'mo', email: 'mo@cakeside.com', password: 'password', password_confirmation: 'password' }
+
+      expect(User.count).to eql(1)
+      expect(response).to redirect_to(my_root_path)
+    end
+
+    it 'displays errors' do
+      post :create, user: { name: 'mo', email: 'mo', password: 'password', password_confirmation: 'password' }
+      expect(response).to redirect_to(new_session_path)
+      expect(flash[:error]).to_not be_empty
+    end
+  end
+end
spec/models/user_spec.rb
@@ -18,6 +18,22 @@ describe User do
     it { should respond_to :avatar }
   end
 
+  describe "validations" do
+    subject { build(:user) }
+
+    it 'validates the email' do
+      subject.email = 'blah'
+      expect(subject.valid?).to be_falsey
+      expect(subject.errors[:email]).to_not be_empty
+    end
+
+    it 'validates the presence of the email' do
+      subject.email = nil
+      expect(subject.valid?).to be_falsey
+      expect(subject.errors[:email]).to_not be_empty
+    end
+  end
+
   describe "when a website url is supplied" do
     describe "when the url is valid" do
       let(:user) { build(:user) }