From a3a09e845fad118537df24021c58b4020473cc34 Mon Sep 17 00:00:00 2001 From: Andrew Tomaka Date: Thu, 1 Aug 2024 21:33:02 -0400 Subject: [PATCH] Create fake model for session --- app/models/session.rb | 22 ++++++++++++++++++++++ config/routes.rb | 1 + test/models/session_test.rb | 25 +++++++++++++++++++++++++ 3 files changed, 48 insertions(+) create mode 100644 app/models/session.rb create mode 100644 test/models/session_test.rb diff --git a/app/models/session.rb b/app/models/session.rb new file mode 100644 index 0000000..c82ce7b --- /dev/null +++ b/app/models/session.rb @@ -0,0 +1,22 @@ +class Session + include ActiveModel::Model + + include ActiveModel::Attributes + include ActiveModel::Validations + + attr_accessor :user_id + + attribute :email, :string + attribute :password, :string + + validates :email, presence: true + validates :password, presence: true + + def save + user = User.authenticate_by(email: email, password: password) + + @user_id = user && user.id + + user.present? && self || nil + end +end diff --git a/config/routes.rb b/config/routes.rb index 74d76c3..7f2460c 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,4 +1,5 @@ Rails.application.routes.draw do + resources :sessions, only: %i[new create destroy] resources :users resources :credit_card_bills resource :dashboard, only: :show diff --git a/test/models/session_test.rb b/test/models/session_test.rb new file mode 100644 index 0000000..5494b76 --- /dev/null +++ b/test/models/session_test.rb @@ -0,0 +1,25 @@ +require "test_helper" + +class SessionTest < ActiveSupport::TestCase + def test_save_when_exists + user = users(:one) + + session = Session.new(email: user.email, password: "secret") + + assert session.save + end + + def test_save_when_not_exists + session = Session.new(email: "fake@example.org", password: "secret") + + refute session.save + end + + def test_save_when_password_incorrect + user = users(:one) + + session = Session.new(email: user.email, password: "bad_password") + + refute session.save + end +end