Skip to content

Commit

Permalink
Refactor service object and add unit test
Browse files Browse the repository at this point in the history
  • Loading branch information
leesmith committed Aug 10, 2015
1 parent 4e72684 commit c333f8f
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 5 deletions.
3 changes: 2 additions & 1 deletion app/controllers/sessions_controller.rb
Expand Up @@ -6,7 +6,8 @@ def new

def create
user = User.where("email = ?", params[:email].downcase).first
if AuthenticateUser.call(user, params)
authentication = AuthenticateUser.new(user, params).call
if authentication.success?
set_cookie(user, params)
redirect_to(sign_in_destination)
else
Expand Down
19 changes: 15 additions & 4 deletions app/services/authenticate_user.rb
@@ -1,11 +1,22 @@
class AuthenticateUser

def self.call(user, params)
if user && user.authenticate(params[:password])
true
def initialize(user, params)
@user = user
@params = params
@result = false
end

def call
if @user && @user.authenticate(@params[:password])
@result = true
else
false
@result = false
end
self
end

def success?
@result
end

end
32 changes: 32 additions & 0 deletions spec/services/authenticate_user_spec.rb
@@ -0,0 +1,32 @@
require 'rails_helper'

RSpec.describe AuthenticateUser do

subject { AuthenticateUser.new(user, params).call }

describe 'for unknown user' do
let(:user) { nil }
let(:params) { {} }
it 'is unsuccessful' do
expect(subject.success?).to be false
end
end

describe 'for known user' do
let(:user) { Fabricate.build(:user) }

context 'with correct password' do
let(:params) { { password: user.password } }
it 'is successful' do
expect(subject.success?).to be true
end
end

context 'with incorrect password' do
let(:params) { { password: 'wrongpassword' } }
it 'is unsuccessful' do
expect(subject.success?).to be false
end
end
end
end

0 comments on commit c333f8f

Please sign in to comment.