repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/factories/requirements.rb
spec/factories/requirements.rb
# frozen_string_literal: true # Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :requirement do id { generate(:unique_id) } contact_name 'Adam Bray' description 'You must attend a training session with Adam before using '\ 'this equipment.' contact_info 'adam.bray@yale.edu' end factory :another_requirement, class: Requirement do contact_name 'Austin Czarnecki' description 'You must attend a training session with Austin before '\ 'using this equipment.' contact_info 'austin.czarnecki@yale.edu' end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/factories/_sequences.rb
spec/factories/_sequences.rb
# frozen_string_literal: true FactoryGirl.define do sequence :name do |n| "Name#{n}" end sequence :serial do |n| "FLKJDSF#{n}" end sequence :sort_order do |n| n end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/controllers/equipment_models_controller_spec.rb
spec/controllers/equipment_models_controller_spec.rb
# frozen_string_literal: true require 'spec_helper' describe EquipmentModelsController, type: :controller do before(:each) { mock_app_config(requests_affect_availability: false) } it_behaves_like 'calendarable', EquipmentModel USER_ROLES = %i[admin user].freeze describe 'GET index' do shared_examples_for 'GET index success' do |user_role| before do mock_user_sign_in(UserMock.new(user_role)) end describe 'basic function' do before { get :index } it_behaves_like 'successful request', :index end it 'defaults to all active equipment models' do # UNSAFE, but a stand in for a relation models = spy('Array') # get around the eager loading allow(models).to receive(:includes).and_return(models) allow(EquipmentModel).to receive(:where).and_return([]) allow(EquipmentModel).to receive(:all).and_return(models) get :index expect(EquipmentModel).to have_received(:all) expect(models).to have_received(:active) end context '@category set' do it 'restricts results to category' do models = spy('Array') cat = CategoryMock.new(traits: [:findable, [:with_equipment_models, models: models]]) allow(models).to receive(:includes).and_return(models) allow(EquipmentModel).to receive(:where).and_return([]) get :index, params: { category_id: cat.id } expect(cat).to have_received(:equipment_models) expect(models).to have_received(:active) end end context 'with show deleted' do it 'populates an array of all equipment models' do models = spy('Array') allow(EquipmentModel).to receive(:where).and_return([]) allow(EquipmentModel).to receive(:all).and_return(models) get :index, params: { show_deleted: true } expect(EquipmentModel).to have_received(:all) expect(models).to have_received(:includes) expect(models).not_to have_received(:active) end end end USER_ROLES.each { |type| it_behaves_like 'GET index success', type } end describe 'GET new' do context 'with admin user' do before do mock_user_sign_in(UserMock.new(:admin)) get :new end it_behaves_like 'successful request', :new it 'assigns a new equipment model to @equipment_model' do expect(assigns(:equipment_model)).to be_new_record expect(assigns(:equipment_model)).to be_kind_of(EquipmentModel) end it 'sets category when one is passed through params' do cat = CategoryMock.new(traits: [:findable]) allow(EquipmentModel).to receive(:new) get :new, params: { category_id: cat.id } expect(EquipmentModel).to have_received(:new).with(category: cat) end end context 'when not admin' do before do mock_user_sign_in get :new end it_behaves_like 'redirected request' end end describe 'POST create' do context 'with admin user' do before { mock_user_sign_in(UserMock.new(:admin)) } context 'successful save' do let!(:model) { FactoryGirl.build_stubbed(:equipment_model) } before do allow(EquipmentModel).to receive(:new).and_return(model) allow(model).to receive(:save).and_return(true) post :create, params: { equipment_model: { name: 'Model' } } end it { is_expected.to set_flash[:notice] } it { is_expected.to redirect_to(model) } end context 'unsuccessful save' do before do model = EquipmentModelMock.new(save: false) post :create, params: { equipment_model: { id: model.id } } end it { is_expected.to set_flash[:error] } it { is_expected.to render_template(:new) } end end context 'when not admin' do before do mock_user_sign_in attr = FactoryGirl.attributes_for(:equipment_model) post :create, params: { equipment_model: attr } end it_behaves_like 'redirected request' end end describe 'PUT update' do context 'with admin user' do before { mock_user_sign_in(UserMock.new(:admin)) } context 'successful update' do let!(:model) { FactoryGirl.build_stubbed(:equipment_model) } before do allow(EquipmentModel).to receive(:find).with(model.id.to_s) .and_return(model) allow(model).to receive(:update).and_return(true) put :update, params: { id: model.id, equipment_model: { name: 'Model' } } end it { is_expected.to set_flash[:notice] } it { is_expected.to redirect_to(model) } end context 'unsuccessful update' do before do model = EquipmentModelMock.new(traits: %i[findable with_category], update: false) put :update, params: { id: model.id, equipment_model: { name: 'Model' } } end it { is_expected.not_to set_flash } it { is_expected.to render_template(:edit) } end end context 'when not admin' do before do mock_user_sign_in put :update, params: { id: 1, equipment_model: { name: 'Model' } } end it_behaves_like 'redirected request' end end describe 'PUT deactivate' do context 'as admin' do before { mock_user_sign_in(UserMock.new(:admin)) } shared_examples 'not confirmed' do |flash_type, **opts| let!(:model) { FactoryGirl.build_stubbed(:equipment_model) } before do allow(EquipmentModel).to receive(:find).with(model.id.to_s) .and_return(model) allow(model).to receive(:destroy) put :deactivate, params: { id: model.id, **opts } end it { is_expected.to set_flash[flash_type] } it { is_expected.to redirect_to(model) } it 'does not deactivate model' do expect(model).not_to have_received(:destroy) end end it_behaves_like 'not confirmed', :error it_behaves_like 'not confirmed', :notice, deactivation_cancelled: true context 'confirmed' do let!(:model) do EquipmentModelMock.new(traits: %i[findable with_category]) end before do request.env['HTTP_REFERER'] = 'where_i_came_from' put :deactivate, params: { id: model.id, deactivation_confirmed: true } end it { is_expected.to set_flash[:notice] } it { is_expected.to redirect_to('where_i_came_from') } it 'deactivates model' do expect(model).to have_received(:destroy) end end context 'with reservations' do it "archives the model's reservations on deactivation" do model = EquipmentModelMock.new(traits: %i[findable with_category]) res = ReservationMock.new # stub out scope chain -- SMELL allow(Reservation).to receive(:for_eq_model).and_return(Reservation) allow(Reservation).to receive(:finalized).and_return([res]) allow(res).to receive(:archive).and_return(res) request.env['HTTP_REFERER'] = 'where_i_came_from' put :deactivate, params: { id: model.id, deactivation_confirmed: true } expect(res).to have_received(:archive) expect(res).to have_received(:save).with(validate: false) end end end context 'not admin' do before do mock_user_sign_in put :deactivate, params: { id: 1 } end it_behaves_like 'redirected request' end end describe 'GET show' do # the current controller method is too complex to be tested # appropriately. FIXME when refactoring the controller let!(:model) { FactoryGirl.create(:equipment_model) } shared_examples 'GET show success' do |user_role| before { mock_user_sign_in(UserMock.new(user_role, requirements: [])) } describe 'basic function' do before { get :show, params: { id: model } } it_behaves_like 'successful request', :show end it 'sets to correct equipment model' do get :show, params: { id: model } expect(assigns(:equipment_model)).to eq(model) end it 'sets @associated_equipment_models' do mod1 = FactoryGirl.create(:equipment_model) model.associated_equipment_models = [mod1] get :show, params: { id: model } expect(assigns(:associated_equipment_models)).to eq([mod1]) end it 'limits @associated_equipment_models to maximum 6' do model.associated_equipment_models = FactoryGirl.create_list(:equipment_model, 7) get :show, params: { id: model } expect(assigns(:associated_equipment_models).size).to eq(6) end end USER_ROLES.each { |type| it_behaves_like 'GET show success', type } context 'with admin user' do before do FactoryGirl.create_pair(:equipment_item, equipment_model: model) sign_in FactoryGirl.create(:admin) end let!(:missed) do FactoryGirl.create(:missed_reservation, equipment_model: model) end let!(:starts_today) do FactoryGirl.create(:reservation, equipment_model: model, start_date: Time.zone.today, due_date: Time.zone.today + 2.days) end let!(:starts_this_week) do FactoryGirl.create(:reservation, equipment_model: model, start_date: Time.zone.today + 2.days, due_date: Time.zone.today + 4.days) end let!(:starts_next_week) do FactoryGirl.create(:reservation, equipment_model: model, start_date: Time.zone.today + 9.days, due_date: Time.zone.today + 11.days) end it 'includes @pending reservations' do get :show, params: { id: model } expect(assigns(:pending)).to \ match_array([starts_today, starts_this_week]) end end end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/controllers/equipment_items_controller_spec.rb
spec/controllers/equipment_items_controller_spec.rb
# frozen_string_literal: true require 'spec_helper' describe EquipmentItemsController, type: :controller do before(:each) { mock_app_config } it_behaves_like 'calendarable', EquipmentItem describe 'GET index' do context 'with admin user' do before { mock_user_sign_in(UserMock.new(:admin)) } describe 'basic function' do before { get :index } it_behaves_like 'successful request', :index end it 'defaults to all active equipment items' do allow(EquipmentItem).to receive(:active) get :index expect(EquipmentItem).to have_received(:active) end context '@equipment_model set' do it 'restricts to the model' do items = spy('Array') model = EquipmentModelMock.new(traits: [:findable, [:with_items, items: items]]) allow(items).to receive(:active) get :index, params: { equipment_model_id: model.id } expect(model).to have_received(:equipment_items) end end context 'show_deleted set' do it 'gets all equipment items' do allow(EquipmentItem).to receive(:all).and_return(EquipmentItem.none) get :index, params: { show_deleted: true } expect(EquipmentItem).to have_received(:all).twice end end end context 'with checkout person user' do before do mock_user_sign_in(UserMock.new(:checkout_person)) get :index end it_behaves_like 'successful request', :index end context 'with normal user' do before do mock_user_sign_in get :index end it_behaves_like 'redirected request' end end describe 'GET show' do context 'with admin user' do let!(:item) { EquipmentItemMock.new(traits: [:findable]) } before do mock_user_sign_in(UserMock.new(:admin)) get :show, params: { id: item.id } end it_behaves_like 'successful request', :show it 'sets to correct equipment item' do expect(EquipmentItem).to have_received(:find).with(item.id.to_s) .at_least(:once) end end context 'with normal user' do before do mock_user_sign_in get :show, params: { id: 1 } end it_behaves_like 'redirected request' end end describe 'GET new' do context 'with admin user' do before do mock_user_sign_in(UserMock.new(:admin)) get :new end it_behaves_like 'successful request', :new it 'assigns a new equipment item to @equipment_item' do expect(assigns(:equipment_item)).to be_new_record expect(assigns(:equipment_item)).to be_kind_of(EquipmentItem) end it 'sets equipment_model when one is passed through params' do model = EquipmentModelMock.new(traits: [:findable]) allow(EquipmentItem).to receive(:new) get :new, params: { equipment_model_id: model.id } expect(EquipmentItem).to have_received(:new) .with(equipment_model: model) end end context 'with normal user' do before do mock_user_sign_in get :new end it_behaves_like 'redirected request', :new end end describe 'POST create' do context 'with admin user' do before { mock_user_sign_in(UserMock.new(:admin, md_link: 'admin')) } let!(:model) { FactoryGirl.build_stubbed(:equipment_model) } let!(:item) do EquipmentItemMock.new(traits: [[:with_model, model: model]]) end context 'successful save' do before do allow(EquipmentItem).to receive(:new).and_return(item) allow(item).to receive(:save).and_return(true) post :create, params: { equipment_item: { id: 1 } } end it { is_expected.to set_flash[:notice] } it { is_expected.to redirect_to(model) } it 'saves item with notes' do expect(item).to have_received(:notes=) expect(item).to have_received(:save) end end context 'unsuccessful save' do before do allow(EquipmentItem).to receive(:new).and_return(item) allow(item).to receive(:save).and_return(false) post :create, params: { equipment_item: { id: 1 } } end it { is_expected.not_to set_flash[:error] } it { is_expected.to render_template(:new) } end end context 'with normal user' do before do mock_user_sign_in post :create, params: { equipment_item: { id: 1 } } end it_behaves_like 'redirected request' end end describe 'PUT update' do context 'with admin user' do before { mock_user_sign_in(UserMock.new(:admin)) } let!(:item) { FactoryGirl.build_stubbed(:equipment_item) } context 'successful update' do before do allow(EquipmentItem).to receive(:find).with(item.id.to_s) .and_return(item) allow(item).to receive(:update) allow(item).to receive(:save).and_return(true) put :update, params: { id: item.id, equipment_item: { id: 3 } } end it { is_expected.to set_flash[:notice] } it { is_expected.to redirect_to(item) } end context 'unsuccessful update' do before do allow(EquipmentItem).to receive(:find).with(item.id.to_s) .and_return(item) allow(item).to receive(:update) allow(item).to receive(:save).and_return(false) put :update, params: { id: item.id, equipment_item: { id: 3 } } end it { is_expected.not_to set_flash } it { is_expected.to render_template(:edit) } end end context 'with normal user' do before do mock_user_sign_in put :update, params: { id: 1, equipment_item: { id: 3 } } end it_behaves_like 'redirected request' end end describe 'PUT deactivate' do context 'with admin user' do before { mock_user_sign_in(UserMock.new(:admin)) } shared_examples 'unsuccessful' do |flash_type, **opts| let!(:model) { FactoryGirl.build_stubbed(:equipment_model) } let!(:item) do EquipmentItemMock.new(traits: [:findable], equipment_model: model) end before { put :deactivate, params: { id: item.id, **opts } } it { is_expected.to set_flash[flash_type] } it { is_expected.to redirect_to(model) } it 'does not deactivate the item' do expect(item).not_to have_received(:deactivate) end end it_behaves_like 'unsuccessful', :notice, deactivation_cancelled: true it_behaves_like 'unsuccessful', :notice, deactivation_cancelled: true, deactivation_reason: 'reason' it_behaves_like 'unsuccessful', :error context 'successful' do let!(:item) { EquipmentItemMock.new(traits: [:findable]) } before do request.env['HTTP_REFERER'] = '/referrer' allow(item).to receive(:current_reservation).and_return(false) put :deactivate, params: { id: item.id, deactivation_reason: 'reason' } end it { is_expected.to redirect_to('/referrer') } it 'deactivates the item' do expect(item).to have_received(:deactivate) .with(hash_including(:user, :reason)) end end context 'with reservation' do let!(:item) { EquipmentItemMock.new(traits: [:findable]) } let!(:res) { ReservationMock.new } before do request.env['HTTP_REFERER'] = '/referrer' allow(item).to receive(:current_reservation).and_return(res) put :deactivate, params: { id: item.id, deactivation_reason: 'reason' } end it 'archives the reservation' do expect(res).to have_received(:archive) end end end context 'with normal user' do before do mock_user_sign_in put :deactivate, params: { id: 1, deactivation_reason: 'reason' } end it_behaves_like 'redirected request' end end describe 'PUT activate' do context 'with admin user' do let!(:item) { EquipmentItemMock.new(traits: [:findable], notes: '') } before do mock_user_sign_in(UserMock.new(:admin, md_link: 'admin')) request.env['HTTP_REFERER'] = '/referrer' put :activate, params: { id: item.id } end it { is_expected.to redirect_to('/referrer') } it 'updates the deactivation reason and the notes' do expect(item).to have_received(:update) .with(hash_including(:deactivation_reason, :notes)) end end context 'with normal user' do before do mock_user_sign_in put :activate, params: { id: 1 } end it_behaves_like 'redirected request' end end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/controllers/import_users_controller_spec.rb
spec/controllers/import_users_controller_spec.rb
# frozen_string_literal: true require 'spec_helper' shared_examples_for 'successful upload' do |filename| before do file = fixture_file_upload(filename, 'text/csv') post :import, params: { csv_upload: file } end it { is_expected.to respond_with(:success) } it { is_expected.not_to set_flash } end shared_examples_for 'failure' do it { is_expected.to redirect_to('where_i_came_from') } it { is_expected.to set_flash } end describe ImportUsersController, type: :controller do before(:each) { mock_app_config } # Ensure that we're not actually searching for people in this test around(:example) do |example| env_wrapper('USE_PEOPLE_API' => nil, 'USE_LDAP' => nil) { example.run } end before(:each) do sign_in FactoryGirl.create(:admin) request.env['HTTP_REFERER'] = 'where_i_came_from' end describe '#import (POST /import_users/imported)' do context 'when the csv is valid' do it_behaves_like 'successful upload', 'valid_users.csv' end context 'when the csv contains invalid UTF-8' do it_behaves_like 'successful upload', 'invalid_utf8_users.csv' end context 'when the header line has spaces' do it_behaves_like 'successful upload', 'header_spaces_users.csv' end context 'with extra blank columns' do it_behaves_like 'successful upload', 'extra_columns_users.csv' end context 'with CR line endings' do it_behaves_like 'successful upload', 'cr_line_endings_users.csv' end context "when the isn't csv uploaded" do before { post :import } it_behaves_like 'failure' end end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/controllers/announcements_controller_spec.rb
spec/controllers/announcements_controller_spec.rb
# frozen_string_literal: true require 'spec_helper' shared_examples_for 'announcements page success' do it { is_expected.to respond_with(:success) } it { is_expected.not_to set_flash } end shared_examples_for 'announcements access denied' do it { is_expected.to redirect_to(root_url) } it { is_expected.to set_flash } end describe AnnouncementsController, type: :controller do before(:each) { mock_app_config } describe 'with admin' do before do sign_in FactoryGirl.create(:admin) end context 'GET index' do before do get :index end it_behaves_like 'announcements page success' it { is_expected.to render_template(:index) } it 'should assign @announcements to all Announcements' do expect(assigns(:announcements)).to eq(Announcement.all) end end context 'GET new' do before do get :new end it 'sets the default announcement' do expect(assigns(:announcement)[:starts_at]).to\ eq(Time.zone.today) expect(assigns(:announcement)[:ends_at]).to\ eq(Time.zone.today + 1.day) end it_behaves_like 'announcements page success' it { is_expected.to render_template(:new) } end context 'GET edit' do before do get :edit, params: { id: FactoryGirl.create(:announcement) } end it_behaves_like 'announcements page success' it { is_expected.to render_template(:edit) } end context 'POST create' do context 'with correct params' do before do @attributes = FactoryGirl.attributes_for(:announcement) post :create, params: { announcement: @attributes } end it 'should create the new announcement' do expect(Announcement.find(assigns(:announcement).id)).not_to be_nil end it 'should pass the correct params' do expect(assigns(:announcement)[:starts_at].to_date).to\ eq(@attributes[:starts_at].to_date) expect(assigns(:announcement)[:ends_at].to_date).to\ eq(@attributes[:ends_at].to_date) end it { is_expected.to redirect_to(announcements_path) } it { is_expected.to set_flash } end context 'with incorrect params' do before do @attributes = FactoryGirl.attributes_for(:announcement) @attributes[:ends_at] = Time.zone.today - 1.day post :create, params: { announcement: @attributes } end it { is_expected.to render_template(:new) } end end context 'PUT update' do before do @new_attributes = FactoryGirl.attributes_for(:announcement) @new_attributes[:message] = 'New Message!!' put :update, params: { id: FactoryGirl.create(:announcement), announcement: @new_attributes } end it 'updates the announcement' do expect(assigns(:announcement)[:message]).to\ eq(@new_attributes[:message]) end end context 'DELETE destroy' do before do delete :destroy, params: { id: FactoryGirl.create(:announcement) } end it 'should delete the announcement' do expect(Announcement.where(id: assigns(:announcement)[:id])).to be_empty end it { is_expected.to redirect_to(announcements_path) } end end context 'is not admin' do before do sign_in FactoryGirl.create(:user) @announcement = FactoryGirl.create(:announcement) @attributes = FactoryGirl.attributes_for(:announcement) end context 'GET index' do before do get :index end it_behaves_like 'announcements access denied' end context 'POST create' do before do post :create, params: { announcement: @attributes } end it_behaves_like 'announcements access denied' end context 'PUT update' do before do put :update, params: { id: @announcement } end it_behaves_like 'announcements access denied' end context 'DELETE destroy' do before do delete :destroy, params: { id: @announcement } end it_behaves_like 'announcements access denied' end end context 'GET hide as' do shared_examples 'can hide announcement' do before do @announcement = FactoryGirl.create(:announcement) request.env['HTTP_REFERER'] = 'where_i_came_from' get :hide, params: { id: @announcement } end it 'should set some cookie values' do name = 'hidden_announcement_ids' jar = request.cookie_jar jar.signed[name] = [@announcement[:id].to_s] expect(response.cookies[name]).to eq(jar[name]) end end context 'superuser' do before do sign_in FactoryGirl.create(:superuser) end it_behaves_like 'can hide announcement' end context 'admin' do before do sign_in FactoryGirl.create(:admin) end it_behaves_like 'can hide announcement' end context 'patron' do before do sign_in FactoryGirl.create(:user) end it_behaves_like 'can hide announcement' end context 'checkout person' do before do sign_in FactoryGirl.create(:checkout_person) end it_behaves_like 'can hide announcement' end context 'guest' do before do sign_in FactoryGirl.create(:guest) end it_behaves_like 'can hide announcement' end context 'banned user' do before do sign_in FactoryGirl.create(:banned) end it_behaves_like 'can hide announcement' end end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/controllers/requirements_controller_spec.rb
spec/controllers/requirements_controller_spec.rb
# frozen_string_literal: true require 'spec_helper' # note, these tests are complex in order to test the admin security features # -- namely, it was necessary to test two contexts for each method: the user # being an admin, and not. describe RequirementsController, type: :controller do before(:each) do mock_app_config @requirement = FactoryGirl.create(:requirement, contact_name: 'Adam Bray') end describe 'GET index' do context 'is admin' do before(:each) do sign_in FactoryGirl.create(:admin) get :index end it { is_expected.to respond_with(:success) } it { is_expected.to render_template(:index) } it { is_expected.not_to set_flash } it 'should populate an array of all requirements' do expect(assigns(:requirements)).to eq([@requirement]) end end context 'not an admin' do it 'should redirect to root url if not an admin' do sign_in FactoryGirl.create(:user) get :index expect(response).to redirect_to(root_url) end end end describe 'GET show' do context 'is an admin' do before(:each) do sign_in FactoryGirl.create(:admin) get :show, params: { id: @requirement } end it { is_expected.to respond_with(:success) } it { is_expected.to render_template(:show) } it { is_expected.not_to set_flash } it 'should set @requirement to the selected requirement' do expect(assigns(:requirement)).to eq(@requirement) end end context 'not an admin' do it 'should redirect to root url if not an admin' do sign_in FactoryGirl.create(:user) get :show, params: { id: @requirement } expect(response).to redirect_to(root_url) end end end describe 'GET new' do context 'is admin' do before(:each) do sign_in FactoryGirl.create(:admin) get :new end it { is_expected.to respond_with(:success) } it { is_expected.to render_template(:new) } it { is_expected.not_to set_flash } it 'assigns a new requirement to @requirement' do expect(assigns(:requirement)).to be_new_record expect(assigns(:requirement).is_a?(Requirement)).to be_truthy end end context 'not an admin' do it 'should redirect to root url if not an admin' do sign_in FactoryGirl.create(:user) get :new expect(response).to redirect_to(root_url) end end end describe 'GET edit' do context 'is admin' do before(:each) do sign_in FactoryGirl.create(:admin) get :edit, params: { id: @requirement } end it 'should set @requirement to the selected requirement' do expect(assigns(:requirement)).to eq(@requirement) end it { is_expected.to respond_with(:success) } it { is_expected.to render_template(:edit) } it { is_expected.not_to set_flash } end context 'not admin' do it 'should redirect to root url if not an admin' do sign_in FactoryGirl.create(:user) get :edit, params: { id: @requirement } expect(response).to redirect_to(root_url) end end end describe 'PUT update' do context 'is admin' do before(:each) do sign_in FactoryGirl.create(:admin) end context 'with valid attributes' do before(:each) do attrs = FactoryGirl.attributes_for(:requirement, contact_name: 'John Doe') put :update, params: { id: @requirement, requirement: attrs } end it 'should set @requirement to the correct requirement' do expect(assigns(:requirement)).to eq(@requirement) end it 'should update the attributes of @requirement' do @requirement.reload expect(@requirement.contact_name).to eq('John Doe') end it { is_expected.to redirect_to(@requirement) } it { is_expected.to set_flash } end context 'with invalid attributes' do before(:each) do attrs = FactoryGirl.attributes_for(:requirement, contact_name: '') put :update, params: { id: @requirement, requirement: attrs } end it 'should not update the attributes of @requirement' do @requirement.reload expect(@requirement.contact_name).not_to eq('') expect(@requirement.contact_name).to eq('Adam Bray') end it { is_expected.to render_template(:edit) } it { is_expected.not_to set_flash } end end context 'not admin' do it 'should redirect to root url if not an admin' do sign_in FactoryGirl.create(:user) get :update, params: { id: @requirement, requirement: FactoryGirl.attributes_for(:requirement) } expect(response).to redirect_to(root_url) end end end describe 'POST create' do context 'is admin' do before(:each) do sign_in FactoryGirl.create(:admin) end context 'with valid attributes' do before(:each) do post :create, params: { requirement: FactoryGirl.attributes_for(:requirement) } end it 'saves a new requirement' do expect do attrs = FactoryGirl.attributes_for(:requirement) post :create, params: { requirement: attrs } end.to change(Requirement, :count).by(1) end it { is_expected.to redirect_to(Requirement.last) } it { is_expected.to set_flash } end context 'with invalid attributes' do before(:each) do attrs = FactoryGirl.attributes_for(:requirement, contact_name: nil) post :create, params: { requirement: attrs } end it 'fails to save a new requirment' do expect do attrs = FactoryGirl.attributes_for(:requirement, contact_name: nil) post :create, params: { requirement: attrs } end.not_to change(Requirement, :count) end it { is_expected.not_to set_flash } it { is_expected.to render_template(:new) } end end context 'not admin' do it 'should redirect to root url if not an admin' do sign_in FactoryGirl.create(:user) post :create, params: { requirement: FactoryGirl.attributes_for(:requirement) } expect(response).to redirect_to(root_url) end end end describe 'DELETE destroy' do context 'is admin' do before(:each) do sign_in FactoryGirl.create(:admin) end it 'assigns the selected requirement to @requirement' do delete :destroy, params: { id: @requirement } expect(assigns(:requirement)).to eq(@requirement) end it 'removes @requirement from the database' do expect do delete :destroy, params: { id: @requirement } end.to change(Requirement, :count).by(-1) end it 'should redirect to the requirements index page' do delete :destroy, params: { id: @requirement } expect(response).to redirect_to requirements_url end end context 'not admin' do it 'should redirect to root url if not an admin' do sign_in FactoryGirl.create(:user) delete :destroy, params: { id: @requirement } expect(response).to redirect_to(root_url) end end end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/controllers/users_controller_spec.rb
spec/controllers/users_controller_spec.rb
# frozen_string_literal: true require 'spec_helper' describe UsersController, type: :controller do before(:each) { mock_app_config } it_behaves_like 'calendarable', User describe 'GET index' do before { mock_user_sign_in(UserMock.new(:admin)) } context 'basic function' do before { get :index } it_behaves_like 'successful request', :index end it 'defaults to active users' do allow(User).to receive(:active).and_return(User.none) get :index expect(User).to have_received(:active) end it 'orders users by username' do allow(User).to receive(:active).and_return(User) allow(User).to receive(:order) get :index expect(User).to have_received(:order).with('username ASC') end context 'with show banned' do it 'should assign users to all users' do allow(User).to receive(:active) get :index, params: { show_banned: true } expect(User).not_to have_received(:active) end end end describe 'GET show' do before { mock_user_sign_in(UserMock.new(:admin)) } let!(:user) do UserMock.new(traits: [:findable], reservations: spy('Array')) end context 'basic function' do before { get :show, params: { id: user.id } } it_behaves_like 'successful request', :show end it "gets the user's reservations" do get :show, params: { id: user.id } expect(user).to have_received(:reservations) end # TODO: tests on the reservations being filtered? context 'with banned user' do before do banned = UserMock.new(:banned, traits: [:findable], reservations: spy('Array')) get :show, params: { id: banned.id } end it { is_expected.to respond_with(:success) } it { is_expected.to set_flash[:error] } end end describe 'POST quick_new' do before { mock_user_sign_in(UserMock.new(:admin)) } it 'gets the username from ldap' do allow(User).to receive(:search) post :quick_new, params: { format: :js, possible_netid: 'csw3' } expect(User).to have_received(:search) end it 'attempts to make a new user from the ldap result' do netid = 'sky3' allow(User).to receive(:search).and_return(netid) allow(User).to receive(:new) post :quick_new, params: { format: :js, possible_netid: netid } expect(User).to have_received(:new).with(netid) end end describe 'POST quick_create' do before { mock_user_sign_in(UserMock.new(:admin)) } it 'creates a new user from the params' do user_params = { username: 'sky3' } allow(User).to receive(:new).and_return(UserMock.new) post :quick_create, params: { format: :js, user: user_params } expect(User).to have_received(:new).with(user_params) end it 'sets the role to normal if not given' do user = UserMock.new user_params = { username: 'sky3' } allow(User).to receive(:new).and_return(user) post :quick_create, params: { format: :js, user: user_params } expect(user).to have_received(:role=).with('normal') end it 'sets the view mode to the role' do user = UserMock.new(role: 'role') user_params = { username: 'sky3' } allow(User).to receive(:new).and_return(user) post :quick_create, params: { format: :js, user: user_params } expect(user).to have_received(:view_mode=).with('role') end context 'using CAS' do around(:example) do |example| env_wrapper('CAS_AUTH' => '1') { example.run } end it 'sets the cas login to the username param' do user = UserMock.new user_params = { username: 'sky3' } allow(User).to receive(:new).and_return(user) post :quick_create, params: { format: :js, user: user_params } expect(user).to have_received(:cas_login=).with('sky3') end end context 'successful save' do let!(:user) { UserMock.new(save: true, id: 1) } before do user_params = { username: 'sky3' } allow(User).to receive(:new).and_return(user) post :quick_create, params: { format: :js, user: user_params } end it "sets the cart's user to the new user" do expect(session[:cart].reserver_id).to eq(user.id) end it { is_expected.to set_flash[:notice] } # TODO: render action test? end context 'unsuccessful save' do # TODO: render action test? end end describe 'GET new' do context 'using CAS' do around(:example) do |example| env_wrapper('CAS_AUTH' => '1') { example.run } end context 'with current user' do before { mock_user_sign_in(UserMock.new(:admin)) } it 'initializes a new user' do allow(User).to receive(:new) get :new expect(User).to have_received(:new).at_least(:once) end end end context 'without CAS' do it 'initializes a new user' do mock_user_sign_in(UserMock.new(:admin)) allow(User).to receive(:new) get :new expect(User).to have_received(:new).at_least(:once) end end end describe 'POST create' do before { mock_user_sign_in(UserMock.new(:admin)) } it 'initializes a new user from the params' do user_params = { username: 'sky3' } allow(User).to receive(:new).and_return(UserMock.new) post :create, params: { user: user_params } expect(User).to have_received(:new).with(user_params).at_least(:once) end it 'sets the role to normal if not given' do user = UserMock.new user_params = { username: 'sky3' } allow(User).to receive(:new).and_return(user) post :create, params: { user: user_params } expect(user).to have_received(:role=).with('normal') end it 'sets the view mode to the role' do user = UserMock.new(role: 'role') user_params = { username: 'sky3' } allow(User).to receive(:new).and_return(user) post :create, params: { user: user_params } expect(user).to have_received(:view_mode=).with('role') end context 'using CAS' do around(:example) do |example| env_wrapper('CAS_AUTH' => '1') { example.run } end it 'sets the cas login from params' do user = UserMock.new user_params = { username: 'sky3' } allow(User).to receive(:new).and_return(user) post :create, params: { user: user_params } expect(user).to have_received(:cas_login=).with('sky3') end end context 'without CAS' do before { mock_user_sign_in(UserMock.new(:admin)) } it 'sets the username to the email' do user = UserMock.new(email: 'email') allow(User).to receive(:new).and_return(user) post :create, params: { user: { first_name: 'name' } } expect(user).to have_received(:username=).with('email') end end context 'successful save' do before { mock_user_sign_in(UserMock.new(:admin)) } let!(:user) { FactoryGirl.build_stubbed(:user) } before do allow(User).to receive(:new).and_return(user) allow(user).to receive(:save).and_return(true) post :create, params: { user: { first_name: 'name' } } end it { is_expected.to set_flash[:notice] } it { is_expected.to redirect_to(user) } end context 'unsuccessful save' do before { mock_user_sign_in(UserMock.new(:admin)) } let!(:user) { UserMock.new(save: false) } before do allow(User).to receive(:new).and_return(user) post :create, params: { user: { first_name: 'name' } } end it { is_expected.to render_template(:new) } end end describe 'PUT ban' do before { mock_user_sign_in(UserMock.new(:admin)) } before { request.env['HTTP_REFERER'] = 'where_i_came_from' } context 'guest user' do before do user = UserMock.new(:guest, traits: [:findable]) put :ban, params: { id: user.id } end it_behaves_like 'redirected request' end context 'user is self' do before do user = UserMock.new(:admin, traits: [:findable]) mock_user_sign_in user put :ban, params: { id: user.id } end it_behaves_like 'redirected request' end context 'able to ban' do let!(:user) { UserMock.new(traits: [:findable]) } before { put :ban, params: { id: user.id } } it_behaves_like 'redirected request' it 'should make the user banned' do expect(user).to have_received(:update) .with(hash_including(role: 'banned', view_mode: 'banned')) end end end describe 'PUT unban' do before { mock_user_sign_in(UserMock.new(:admin)) } before { request.env['HTTP_REFERER'] = 'where_i_came_from' } context 'guest user' do before do user = UserMock.new(:guest, traits: [:findable]) put :unban, params: { id: user.id } end it_behaves_like 'redirected request' end context 'able to unban' do let!(:user) { UserMock.new(:banned, traits: [:findable]) } before { put :unban, params: { id: user.id } } it_behaves_like 'redirected request' it 'should make the user banned' do expect(user).to have_received(:update) .with(hash_including(role: 'normal', view_mode: 'normal')) end end end describe 'PUT find' do before { mock_user_sign_in(UserMock.new(:admin)) } context 'no fake searched id' do before do request.env['HTTP_REFERER'] = 'where_i_came_from' put :find, params: { fake_searched_id: '' } end it { is_expected.to set_flash[:alert] } it_behaves_like 'redirected request' end context 'no searched id' do context 'user found' do let!(:username) { 'sky3' } let!(:user) { FactoryGirl.build_stubbed(:user, username: username) } before do allow_any_instance_of(described_class).to \ receive(:get_autocomplete_items).with(term: username) .and_return([user]) put :find, params: { fake_searched_id: username, searched_id: '' } end it 'redirects to found user' do expect(response).to \ redirect_to(manage_reservations_for_user_path(user.id)) end end context 'user not found' do before do request.env['HTTP_REFERER'] = 'where_i_came_from' put :find, params: { fake_searched_id: 'sky3', searched_id: '' } end it { is_expected.to set_flash[:alert] } it_behaves_like 'redirected request' end end context 'with searched id' do let!(:username) { 'sky3' } let!(:user) { FactoryGirl.build_stubbed(:user, username: username) } before do allow(User).to receive(:find).with(user.id.to_s).and_return(user) put :find, params: { fake_searched_id: username, searched_id: user.id } end it 'redirects to found user' do expect(response).to \ redirect_to(manage_reservations_for_user_path(user.id)) end end end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/controllers/app_configs_controller_spec.rb
spec/controllers/app_configs_controller_spec.rb
# frozen_string_literal: true require 'spec_helper' # Routes: # # match '/app_configs/' => 'app_configs#edit', :as => :edit_app_configs # resources :app_configs, :only => [:update] # # match '/new_app_configs' => 'application_setup#new_app_configs', :as => # :new_app_configs # match '/create_app_configs' => 'application_setup#create_app_configs', :as # => :create_app_configs describe AppConfigsController, type: :controller do NON_SUPERUSERS = %i[user admin checkout_person banned guest].freeze describe 'GET edit' do context 'app_config exists already' do before(:each) do @app_config = FactoryGirl.create(:app_config) end context 'user is admin' do before(:each) do sign_in FactoryGirl.create(:admin) get :edit end it { is_expected.to render_template(:edit) } it { is_expected.to respond_with(:success) } it { is_expected.not_to set_flash } it 'should assign @app_config variable to the first appconfig in '\ 'the db' do expect(assigns(:app_config)).to eq(AppConfig.first) end end context 'user is not admin' do before(:each) do sign_in FactoryGirl.create(:user) get :edit end it { is_expected.to redirect_to(root_path) } end end context 'app_config does not exist yet' do before(:each) do sign_in FactoryGirl.create(:user) get :edit end # Commented out 2014/12/18 - these two tests have been failing # intermittently since Devise was implemented (see issues #2 and #1059). # Since they are pretty unimportant we're commenting them out to ensure # a useful test suite # it { is_expected.to respond_with(:success) } it { is_expected.to set_flash } # it { is_expected.to render_template('application_setup/index') } end end describe 'POST update' do context 'app config already exists' do before(:each) do AppConfig.destroy_all @app_config = FactoryGirl.create(:app_config) end context 'user is admin' do before(:each) do sign_in FactoryGirl.create(:admin) # Except paperclip attributes that trigger MassAssignment errors @params = FactoryGirl.attributes_for(:app_config) .reject do |k, _v| %i[favicon_file_name favicon_content_type favicon_file_size favicon_updated_at].include? k end end it 'assigns current configuration to @app_config' do post :update, params: { id: @app_config.id, app_config: @params } expect(assigns(:app_config)).to eq(@app_config) end # TODO: FIXME context 'With valid parameters' do # TODO: Simulate successful ActiveRecord update call it 'resets TOS status for all users when :reset_tos_for_users is 1' do @user = FactoryGirl.create(:user) @params = @params.merge(reset_tos_for_users: 1) Rails.logger.debug @params put :update, params: { id: @app_config.id, app_config: @params } @user.reload expect(@user.terms_of_service_accepted).to be_falsey end it 'maintains TOS status for all users when :reset_tos_for_users '\ 'is not 1' do @user = FactoryGirl.create(:user) @params = @params.merge(reset_tos_for_users: 0) Rails.logger.debug @params post :update, params: { id: @app_config.id, app_config: @params } @user.reload expect(@user.terms_of_service_accepted).to be_truthy end it 'correctly sets missing_phone flag for users when toggling '\ ':require_phone' do @user = FactoryGirl.create(:no_phone) expect(@user.missing_phone).to be_falsey @params = @params.merge(require_phone: 1) Rails.logger.debug @params post :update, params: { id: @app_config.id, app_config: @params } @user.reload expect(@user.missing_phone).to be_truthy end it 'restores favicon when appropriate' # it { should respond_with(:success) } # it { should redirect_to(catalog_path) } end context 'With invalid parameters' do # TODO: Simulate update failure before(:each) do # Except paperclip attributes that trigger MassAssignment errors @params = FactoryGirl.attributes_for(:app_config, site_title: nil) .reject do |k, _v| %i[favicon_file_name favicon_content_type favicon_file_size favicon_updated_at].include? k end post :update, params: { id: @app_config.id, app_config: @params } end # it { should render_template(:edit) } end end context 'user is not admin' do before(:each) do sign_in FactoryGirl.create(:user) post :update, params: { id: 1 } end it { is_expected.to redirect_to(root_path) } end end context 'app_config does not exist yet' do before(:each) do sign_in FactoryGirl.create(:user) post :update, params: { id: 1 } end it { is_expected.to respond_with(:success) } it { is_expected.to set_flash } it { is_expected.to render_template('application_setup/index') } end end describe '#run_daily_tasks (PUT /app_configs/run_daily_tasks)' do before(:each) do mock_app_config request.env['HTTP_REFERER'] = 'where_i_came_from' end context 'as superuser' do before(:each) do sign_in FactoryGirl.create(:superuser) end it 'enqueues the daily tasks' do expect(DailyTasksJob).to receive(:perform_now) put :run_daily_tasks end end shared_examples 'as other users' do |user| before(:each) do sign_in FactoryGirl.create(user) end it "doesn't enqueue the daily tasks" do expect(DailyTasksJob).to_not receive(:perform_now) put :run_daily_tasks end end NON_SUPERUSERS.each { |u| it_behaves_like 'as other users', u } end describe '#run_hourly_tasks (PUT /app_configs/run_hourly_tasks)' do before(:each) do mock_app_config request.env['HTTP_REFERER'] = 'where_i_came_from' end context 'as superuser' do before(:each) do sign_in FactoryGirl.create(:superuser) end it 'enqueues the hourly tasks' do expect(HourlyTasksJob).to receive(:perform_now) put :run_hourly_tasks end end shared_examples 'as other users' do |user| before(:each) do sign_in FactoryGirl.create(user) end it "doesn't enqueue the hourly tasks" do expect(HourlyTasksJob).to_not receive(:perform_now) put :run_hourly_tasks end end NON_SUPERUSERS.each { |u| it_behaves_like 'as other users', u } end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/controllers/application_controller_spec.rb
spec/controllers/application_controller_spec.rb
# frozen_string_literal: true require 'spec_helper' describe ApplicationController, type: :controller do before(:each) do @app_config = FactoryGirl.create(:app_config) # this is to ensure that all before_actions are run @first_user = FactoryGirl.create(:user) allow(controller).to receive(:app_setup_check) allow(controller).to receive(:load_configs) allow(controller).to receive(:seen_app_configs) allow(controller).to receive(:cart) allow(controller).to receive(:fix_cart_date) allow(controller).to receive(:set_view_mode) allow(controller).to receive(:make_cart_compatible) sign_in FactoryGirl.create(:user) end # TODO: This may involve rewriting the method somewhat describe 'PUT reload_catalog_cart' do before(:each) do session[:cart] = Cart.new session[:cart].reserver_id = @first_user.id session[:cart].start_date = (Time.zone.today + 1.day) session[:cart].due_date = (Time.zone.today + 2.days) equipment_model = FactoryGirl.create(:equipment_model, category: FactoryGirl.create(:category)) FactoryGirl.create(:equipment_item, equipment_model_id: equipment_model.id) session[:cart].add_item(equipment_model) @new_reserver = FactoryGirl.create(:user) end context 'valid parameters' do it 'should update cart dates' do new_start = Time.zone.today + 3.days new_end = Time.zone.today + 4.days put :reload_catalog_cart, params: { cart: { start_date_cart: new_start, due_date_cart: new_end }, reserver_id: @new_reserver.id } expect(session[:cart].start_date).to eq(new_start) expect(session[:cart].due_date).to eq(new_end) expect(session[:cart].reserver_id).to eq(@new_reserver.id.to_s) end it 'should not set the flash' do expect(flash).to be_empty end end context 'invalid parameters' do it 'should set the flash' do new_start = Time.zone.today - 300.days new_end = Time.zone.today + 4000.days put :reload_catalog_cart, params: { cart: { start_date_cart: new_start.strftime('%m/%d/%Y'), due_date_cart: new_end.strftime('%m/%d/%Y') }, reserver_id: @new_reserver.id } expect(flash).not_to be_empty end end context 'banned reserver' do it 'should set the flash' do put :reload_catalog_cart, params: { cart: { start_date_cart: Time.zone.today, due_date_cart: Time.zone.today + 1.day }, reserver_id: FactoryGirl.create(:banned).id } expect(flash[:error].strip).not_to eq('') end end end describe 'DELETE empty_cart' do before(:each) do session[:cart] = Cart.new session[:cart].reserver_id = @first_user.id delete :empty_cart end it 'empties the cart' do expect(session[:cart].items).to be_empty end it { is_expected.to redirect_to(root_path) } it { is_expected.to set_flash } end describe 'GET terms_of_service' do before(:each) do @app_config = FactoryGirl.create(:app_config) controller.instance_variable_set(:@app_configs, @app_config) get :terms_of_service end it { is_expected.to render_template('terms_of_service/index') } it 'assigns @app_config.terms_of_service to @tos' do expect(assigns(:tos)).to eq(@app_config.terms_of_service) end end describe 'PUT deactivate' do it 'should assign @objects_class2 to the object and controller '\ 'specified by params' it 'should delete @objects_class2' it 'should set the flash' it 'should redirect to request.referer' end describe 'PUT activate' do it 'should assign @model_to_activate to the model to be activated' it 'should call activatParents on the assigned model' it 'should revive @model_to_activate' it 'should set the flash' it 'should redirect to request.referer' end describe 'GET markdown_help' do before(:each) do get :markdown_help end it { is_expected.to render_template('shared/_markdown_help') } # TODO: not sure how to make sure that the js template is being rendered # as well. end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/controllers/contact_controller_spec.rb
spec/controllers/contact_controller_spec.rb
# frozen_string_literal: true require 'spec_helper' describe ContactController, type: :controller do before(:each) do @category = FactoryGirl.create(:category) sign_in FactoryGirl.create(:user) # goes after the above to skip certain user validations @ac = mock_app_config(contact_email: 'contact@email.com', admin_email: 'admin@email.com', site_title: 'Reservations Specs') end describe 'GET new' do before(:each) do get :new end it 'should assign @message to a new message' do expect(assigns(:message).is_a?(Message)).to be_truthy end it { is_expected.to respond_with(:success) } it { is_expected.to render_template(:new) } it { is_expected.not_to set_flash } end describe 'POST create' do before(:each) do ActionMailer::Base.deliveries = nil end context 'with valid attributes' do before(:each) do post :create, params: { message: FactoryGirl.attributes_for(:message) } end it 'sends a message' do expect(ActionMailer::Base.deliveries.last.subject).to\ eq('[Reservations Specs] ' + FactoryGirl.build(:message).subject) end it { is_expected.to redirect_to(root_path) } it { is_expected.to set_flash } end context 'with invalid attributes' do before(:each) do attrs = FactoryGirl.attributes_for(:message, name: nil) post :create, params: { message: attrs } end it { is_expected.to render_template(:new) } it { is_expected.to set_flash } it 'should not send a message' do expect(ActionMailer::Base.deliveries).to eq([]) end end end context 'with contact e-mail set' do before do allow(@ac).to receive(:contact_link_location) .and_return('contact@example.com') post :create, params: { message: FactoryGirl.attributes_for(:message) } end it 'sends the message to the contact address' do expect(ActionMailer::Base.deliveries.last.to).to\ include('contact@example.com') end end context 'with contact e-mail not set' do before do allow(@ac).to receive(:contact_link_location).and_return('') post :create, params: { message: FactoryGirl.attributes_for(:message) } end it 'sends the message to the admin address' do expect(ActionMailer::Base.deliveries.last.to).to\ include(AppConfig.check(:admin_email)) end end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/controllers/blackouts_controller_spec.rb
spec/controllers/blackouts_controller_spec.rb
# frozen_string_literal: true require 'spec_helper' shared_examples_for 'blackouts page success' do it { is_expected.to respond_with(:success) } it { is_expected.not_to set_flash } end shared_examples_for 'blackouts access denied' do it { is_expected.to redirect_to(root_url) } it { is_expected.to set_flash } end describe BlackoutsController, type: :controller do before(:each) { mock_app_config } describe 'with admin' do before do sign_in FactoryGirl.create(:admin) end context 'GET index' do before do get :index end it_behaves_like 'blackouts page success' it { is_expected.to render_template(:index) } it 'should assign @blackouts to all blackouts' do expect(assigns(:blackouts)).to eq(Blackout.all) end end context 'GET show' do before do get :show, params: { id: FactoryGirl.create(:blackout) } end it_behaves_like 'blackouts page success' it { is_expected.to render_template(:show) } context 'single blackout' do it 'should not display a set' do expect(assigns(:blackout_set).nil?) end end end context 'GET show' do before do @blackout = FactoryGirl.create(:blackout, set_id: 1) @blackout_set = Blackout.where(set_id: 1) get :show, params: { id: @blackout } end it_behaves_like 'blackouts page success' context 'recurring blackout' do it 'should display the correct set' do expect(assigns(:blackout_set).uniq.sort).to\ eq(@blackout_set.uniq.sort) end # the above code doesn't work; i'm too much of an rspec newbie end end context 'GET new' do before do get :new end it_behaves_like 'blackouts page success' it { is_expected.to render_template(:new) } end context 'GET new_recurring' do before do get :new_recurring end it_behaves_like 'blackouts page success' it { is_expected.to render_template(:new_recurring) } end context 'GET edit' do before do get :edit, params: { id: FactoryGirl.create(:blackout) } end it_behaves_like 'blackouts page success' it { is_expected.to render_template(:edit) } end context 'POST create_recurring' do context 'with correct params' do before do @new_set_id = Blackout.last ? Blackout.last.id + 1 : 0 @attributes = FactoryGirl.attributes_for(:blackout, days: ['1', '']) post :create_recurring, params: { blackout: @attributes } end it 'should create a set' do expect(Blackout.where(set_id: @new_set_id)).not_to be_empty end it { is_expected.to redirect_to(blackouts_path) } it { is_expected.to set_flash } end context 'with incorrect params' do before do request.env['HTTP_REFERER'] = 'where_i_came_from' @attributes = FactoryGirl.attributes_for(:blackout, days: ['']) post :create_recurring, params: { blackout: @attributes } end it { is_expected.to set_flash } it { is_expected.to render_template('new_recurring') } end context 'with conflicting reservation' do before do @res = FactoryGirl.create(:valid_reservation, due_date: Time.zone.today + 1.day) @attributes = FactoryGirl.attributes_for( :blackout, days: [(Time.zone.today + 1.day).wday.to_s] ) post :create_recurring, params: { blackout: @attributes } end it { is_expected.to set_flash } it { is_expected.to render_template('new_recurring') } it 'should not save the blackouts' do p = { blackout: @attributes } expect { post :create_recurring, params: p }.not_to \ change { Blackout.all.count } end end end context 'POST create' do shared_examples_for 'creates blackout' do |attributes| before { post :create, params: { blackout: attributes } } it 'should create the new blackout' do expect(Blackout.find(assigns(:blackout).id)).not_to be_nil end it 'should pass the correct params' do expect(assigns(:blackout)[:notice]).to eq(attributes[:notice]) expect(assigns(:blackout)[:start_date]).to\ eq(attributes[:start_date]) expect(assigns(:blackout)[:end_date]).to eq(attributes[:end_date]) expect(assigns(:blackout)[:blackout_type]).to\ eq(attributes[:blackout_type]) end it { is_expected.to redirect_to(blackout_path(assigns(:blackout))) } it { is_expected.to set_flash } end shared_examples_for 'does not create blackout' do |attributes| before { post :create, params: { blackout: attributes } } it { is_expected.to set_flash } it { is_expected.to render_template(:new) } it 'should not save the blackout' do expect { post :create, params: { blackout: attributes } }.not_to \ change { Blackout.all.count } end end context 'with correct params' do attributes = FactoryGirl.attributes_for(:blackout) it_behaves_like 'creates blackout', attributes end context 'with overlapping archived reservation' do before do FactoryGirl.create(:archived_reservation, start_date: Time.zone.today + 1.day, due_date: Time.zone.today + 3.days) end attributes = FactoryGirl.attributes_for(:blackout, start_date: Time.zone.today, end_date: Time.zone.today + 2.days) it_behaves_like 'creates blackout', attributes end context 'with overlapping missed reservation' do before do FactoryGirl.create(:missed_reservation, start_date: Time.zone.today + 1.day, due_date: Time.zone.today + 3.days) end attributes = FactoryGirl.attributes_for(:blackout, start_date: Time.zone.today, end_date: Time.zone.today + 2.days) it_behaves_like 'creates blackout', attributes end context 'with incorrect params' do attributes = FactoryGirl.attributes_for(:blackout, end_date: Time.zone.today - 1.day) it_behaves_like 'does not create blackout', attributes end context 'with conflicting reservation start date' do before do FactoryGirl.create(:valid_reservation, start_date: Time.zone.today + 1.day, due_date: Time.zone.today + 3.days) end attributes = FactoryGirl.attributes_for(:blackout, start_date: Time.zone.today, end_date: Time.zone.today + 2.days) it_behaves_like 'does not create blackout', attributes end context 'with conflicting reservation due date' do before do FactoryGirl.create(:valid_reservation, start_date: Time.zone.today, due_date: Time.zone.today + 2.days) end attributes = FactoryGirl.attributes_for(:blackout, start_date: Time.zone.today + 1.day, end_date: Time.zone.today + 3.days) it_behaves_like 'does not create blackout', attributes end end context 'PUT update' do shared_examples_for 'does not update blackout' do |attributes| before do put :update, params: { id: FactoryGirl.create(:blackout), blackout: attributes } assigns(:blackout).reload end it { is_expected.to set_flash[:error] } it { is_expected.to render_template(:edit) } it 'should not save the blackout' do expect(assigns(:blackout)[:notice]).not_to eq(attributes[:notice]) end end context 'single blackout' do before do @new_attributes = FactoryGirl.attributes_for(:blackout) @new_attributes[:notice] = 'New Message!!' put :update, params: { id: FactoryGirl.create(:blackout), blackout: @new_attributes } end it 'updates the blackout' do expect(assigns(:blackout)[:notice]).to eq(@new_attributes[:notice]) end end context 'recurring blackout' do before do @new_attributes = FactoryGirl.attributes_for(:blackout) @new_attributes[:notice] = 'New Message!!' put :update, params: { id: FactoryGirl.create(:blackout, set_id: 1), blackout: @new_attributes } end it 'updates the blackout' do expect(assigns(:blackout)[:notice]).to eq(@new_attributes[:notice]) end it 'sets the set_id to nil' do expect(assigns(:blackout)[:set_id]).to be_nil end end context 'single blackout with conflicting reservation' do before do FactoryGirl.create(:valid_reservation, start_date: Time.zone.today, due_date: Time.zone.today) FactoryGirl.create(:blackout, start_date: Time.zone.today + 1.day, end_date: Time.zone.today + 1.day) end attributes = FactoryGirl.attributes_for(:blackout, notice: 'New Message!!', start_date: Time.zone.today) it_behaves_like 'does not update blackout', attributes end context 'recurring blackout with conflicting reservation' do before do FactoryGirl.create(:valid_reservation, start_date: Time.zone.today, due_date: Time.zone.today) FactoryGirl.create(:blackout, set_id: 1, start_date: Time.zone.today + 1.day, end_date: Time.zone.today + 1.day) end attributes = FactoryGirl.attributes_for(:blackout, notice: 'New Message!!', start_date: Time.zone.today) it_behaves_like 'does not update blackout', attributes end context 'updating with invalid params' do before do FactoryGirl.create(:blackout, start_date: Time.zone.today, end_date: Time.zone.today + 1.day) end attributes = FactoryGirl.attributes_for(:blackout, notice: 'New Message!!', end_date: Time.zone.today - 7.days) it_behaves_like 'does not update blackout', attributes end end context 'DELETE destroy' do before do delete :destroy, params: { id: FactoryGirl.create(:blackout) } end it 'should delete the blackout' do expect(Blackout.where(id: assigns(:blackout)[:id])).to be_empty end it { is_expected.to redirect_to(blackouts_path) } end context 'DELETE destroy recurring' do before do # create an extra instance to test that the whole set was deleted @extra = FactoryGirl.create(:blackout, set_id: 1) delete :destroy_recurring, params: { id: FactoryGirl.create(:blackout, set_id: 1) } end it 'should delete the whole set' do expect(Blackout.where(set_id: @extra[:set_id])).to be_empty end it { is_expected.to set_flash } it { is_expected.to redirect_to(blackouts_path) } end end context 'is not admin' do before do sign_in FactoryGirl.create(:user) @blackout = FactoryGirl.create(:blackout) @attributes = FactoryGirl.attributes_for(:blackout) end context 'GET index' do before do get :index end it_behaves_like 'blackouts access denied' end context 'GET show' do before do get :show, params: { id: @blackout } end it_behaves_like 'blackouts access denied' end context 'POST create' do before do post :create, params: { blackout: @attributes } end it_behaves_like 'blackouts access denied' end context 'PUT update' do before do put :update, params: { id: @blackout } end it_behaves_like 'blackouts access denied' end context 'POST create recurring' do before do post :create_recurring, params: { blackout: @attributes } end it_behaves_like 'blackouts access denied' end context 'DELETE destroy' do before do delete :destroy, params: { id: @blackout } end it_behaves_like 'blackouts access denied' end context 'DELETE destroy recurring' do before do delete :destroy_recurring, params: { id: @blackout } end it_behaves_like 'blackouts access denied' end end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/controllers/reservations_controller_spec.rb
spec/controllers/reservations_controller_spec.rb
# frozen_string_literal: true # rubocop:disable Rails/SkipsModelValidations require 'spec_helper' require 'helpers/email_helper_spec' describe ReservationsController, type: :controller do AC_DEFAULTS = { disable_user_emails: false, override_on_create: false, override_at_checkout: false, res_exp_time: false, admin_email: 'admin@email.com' }.freeze before(:each) { mock_app_config(AC_DEFAULTS) } shared_examples 'inaccessible by banned user' do before { mock_user_sign_in(FactoryGirl.build_stubbed(:banned)) } it_behaves_like 'redirected request' end describe '#update_index_dates (PUT)' do before(:each) do mock_user_sign_in list = { start_date: Time.zone.today.to_s, end_date: (Time.zone.today + 1.day).to_s, filter: :reserved } put :update_index_dates, params: { list: list } end it { is_expected.to redirect_to('/reservations') } it 'disables all_date viewing' do expect(session[:all_dates]).to be_falsey end it 'sets the session dates' do expect(session[:index_start_date]).to eq(Time.zone.today) expect(session[:index_end_date]).to eq(Time.zone.today + 1.day) end it 'sets the session filter' do expect(session[:filter]).to eq(:reserved) end end describe '#view_all_dates (PUT)' do before do mock_user_sign_in put :view_all_dates end it { is_expected.to redirect_to('/reservations') } it 'enables all_date viewing' do expect(session[:all_dates]).to be_truthy end end describe '#index (GET /reservations/)' do # SMELLS: # - @filters # - long method # - message chains let!(:time_filtered) { spy('Array') } shared_examples 'filterable' do it 'can filter' do trait = :checked_out get :index, params: { trait => true } expect(time_filtered).to have_received(trait).at_least(:once) end it 'with respect to session[:filter] first' do trait = :checked_out session_trait = :returned session[:filter] = session_trait get :index, params: { trait => true } expect(time_filtered).to have_received(session_trait).at_least(:once) expect(time_filtered).to have_received(trait).at_least(:once) end end context 'normal user' do let!(:user) do res = spy('Array', starts_on_days: time_filtered) UserMock.new(reservations: res) end before(:each) do mock_user_sign_in(user) allow(Reservation).to receive(:starts_on_days) get :index end it { is_expected.to respond_with(:success) } it { is_expected.to render_template(:index) } it "only gets the current user's reservations" do expect(Reservation).not_to have_received(:starts_on_days) expect(user).to have_received(:reservations).at_least(:once) end it 'defaults to reserved' do # twice: once from set_counts, once from filtering expect(time_filtered).to have_received(:reserved).twice end it_behaves_like 'filterable' end context 'admin' do let!(:user) { UserMock.new(:admin) } before(:each) do allow(Reservation).to receive(:starts_on_days) .and_return(time_filtered) mock_user_sign_in(user) get :index end it 'gets all reservations' do expect(Reservation).to have_received(:starts_on_days) end it 'defaults to upcoming' do # twice: once from set_counts, once from filtering expect(time_filtered).to have_received(:upcoming).twice end it_behaves_like 'filterable' end it_behaves_like 'inaccessible by banned user' do before { get :index } end end describe '#new (GET /reservations/new)' do # SMELLS: # - long method # - redirect location set for testing in code ??? # - feature envy # most of this should probably be in the cart? it_behaves_like 'inaccessible by banned user' do before { get :new } end context 'normal user' do let!(:user) { FactoryGirl.build_stubbed(:user) } before(:each) do allow(User).to receive(:find).with(user.id).and_return(user) mock_user_sign_in(user) request.env['HTTP_REFERER'] = 'where_i_came_from' end context 'with an empty cart' do before(:each) { get :new } it { expect(response).to redirect_to('where_i_came_from') } it { is_expected.to set_flash } end context 'with a non-empty cart' do let!(:cart) do instance_spy('Cart', items: { fake_id: 1 }, reserver_id: user.id, start_date: Time.zone.today, due_date: Time.zone.today - 1.day) end context 'without errors' do before(:each) do allow(cart).to receive(:validate_all).and_return('') get :new, params: {}, session: { cart: cart } end it { is_expected.to render_template(:new) } it 'initializes a new reservation' do allow(Reservation).to receive(:new) get :new, params: {}, session: { cart: cart } expect(Reservation).to have_received(:new) end it 'assigns errors' do expect(assigns(:errors)).to eq '' end end context 'with errors' do before do allow(cart).to receive(:validate_all).and_return('error') get :new, params: {}, session: { cart: cart } end it 'assigns errors' do expect(assigns(:errors)).to eq 'error' end it { is_expected.to set_flash[:error] } end end end context 'can override errors' do let!(:user) { FactoryGirl.build_stubbed(:admin) } before(:each) do allow(User).to receive(:find).with(user.id).and_return(user) mock_user_sign_in(user) request.env['HTTP_REFERER'] = 'where_i_came_from' end context 'with a non-empty cart' do before(:each) do @cart = FactoryGirl.build(:cart_with_items, reserver_id: user.id) get :new, params: {}, session: { cart: @cart } end it 'should display errors' do expect(assigns(:errors)).to eq @cart.validate_all end it { is_expected.to render_template(:new) } end end end describe '#create (POST /reservations/create)' do # SMELLS: so, so many of them # not going to refactor this yet before(:all) do @user = FactoryGirl.create(:user) @checkout_person = FactoryGirl.create(:checkout_person) end after(:all) do User.destroy_all end it_behaves_like 'inaccessible by banned user' do before do attr = FactoryGirl.attributes_for(:valid_reservation) post :create, params: { reservation: attr } end end context 'when accessed by non-banned user' do before(:each) { sign_in @user } context 'with validation-failing items in Cart' do before(:each) do @invalid_cart = FactoryGirl.build(:invalid_cart, reserver_id: @user.id) @req = proc do post :create, params: { reservation: { notes: 'because I can' } }, session: { cart: @invalid_cart } end @req_no_notes = proc do post :create, params: { reservation: { notes: '' } }, session: { cart: @invalid_cart } end end context 'no justification provided' do before do sign_in @checkout_person @req_no_notes.call end it { is_expected.to render_template(:new) } it 'should set @notes_required to true' do expect(assigns(:notes_required)).to be_truthy end end context 'and user can override errors' do before(:each) do mock_app_config(AC_DEFAULTS.merge(override_on_create: true)) sign_in @checkout_person end it 'affects the database' do expect { @req.call }.to change { Reservation.count } end it 'sets the reservation notes' do @req.call expect(Reservation.last.notes.empty?).not_to be_truthy end it 'should redirect' do @req.call expect(response).to\ redirect_to(manage_reservations_for_user_path(@user.id)) end it 'sets the flash' do @req.call expect(flash[:notice]).not_to be_nil end end context 'and user cannot override errors' do # request would be filed before(:each) do mock_app_config(AC_DEFAULTS.merge(override_on_create: false)) sign_in @checkout_person end it 'affects database' do expect { @req.call }.to change { Reservation.count } end it 'sets the reservation notes' do @req.call expect(Reservation.last.notes.empty?).not_to be_truthy end it 'redirects to catalog_path' do @req.call expect(response).to redirect_to(catalog_path) end it 'should not set the flash' do @req.call expect(flash[:error]).to be_nil end end end context 'with validation-passing items in Cart' do before(:each) do @valid_cart = FactoryGirl.build(:cart_with_items) @req = proc do post :create, params: { reservation: { start_date: Time.zone.today, due_date: (Time.zone.today + 1.day), reserver_id: @user.id } }, session: { cart: @valid_cart } end end it 'saves items into database' do expect { @req.call }.to change { Reservation.count } end it 'sets the reservation notes' do @req.call expect(Reservation.last.notes.empty?).not_to be_truthy end it 'sets the status to reserved' do @req.call expect(Reservation.last.reserved?) end it 'empties the Cart' do @req.call expect(response.request.env['rack.session'][:cart].items.count) .to eq(0) # Cart.should_receive(:new) end it 'sets flash[:notice]' do @req.call expect(flash[:notice]).not_to be_nil end it 'is a redirect' do @req.call expect(response).to be_redirect end context 'with notify_admin_on_create set' do before(:each) do ActionMailer::Base.deliveries.clear mock_app_config(AC_DEFAULTS.merge(notify_admin_on_create: true)) end it 'cc-s the admin on the confirmation email' do @req.call delivered = ActionMailer::Base.deliveries.last expect(delivered).not_to be_nil expect(delivered.subject).to \ eq('[Reservations] Reservation created') end end context 'without notify_admin_on_create set' do before(:each) do ActionMailer::Base.deliveries.clear mock_app_config(AC_DEFAULTS.merge(notify_admin_on_create: false)) end it 'cc-s the admin on the confirmation email' do @req.call delivered = ActionMailer::Base.deliveries.last expect(delivered).to be_nil end end end context 'with banned reserver' do before(:each) do sign_in @checkout_person @valid_cart = FactoryGirl.build(:cart_with_items) @banned = FactoryGirl.create(:banned) @valid_cart.reserver_id = @banned.id @req = proc do post :create, params: { reservation: { start_date: Time.zone.today, due_date: (Time.zone.today + 1.day), reserver_id: @banned.id, notes: 'because I can' } }, session: { cart: @valid_cart } end end it 'does not save' do expect { @req.call }.not_to change { Reservation.count } end it 'is a redirect' do @req.call expect(response).to be_redirect end it 'sets flash[:error]' do @req.call expect(flash[:error]).not_to be_nil end end end end describe '#edit (GET /reservations/:id/edit)' do # SMELLS: # - message chain it_behaves_like 'inaccessible by banned user' do before { get 'edit', params: { id: 1 } } end context 'when accessed by patron' do before(:each) do mock_user_sign_in get 'edit', params: { id: 1 } end include_examples 'redirected request' end context 'when accessed by checkout person disallowed by settings' do before(:each) do mock_app_config(AC_DEFAULTS.merge(checkout_persons_can_edit: false)) mock_user_sign_in(UserMock.new(:checkout_person)) get 'edit', params: { id: 1 } end include_examples 'redirected request' end shared_examples 'can access edit page' do let!(:item) { EquipmentItemMock.new(id: 1, name: 'Name') } before do model = EquipmentModelMock.new(traits: [[:with_item, item: item]]) res = ReservationMock.new(equipment_model: model, id: 1, class: Reservation) allow(Reservation).to receive(:find).with(res.id.to_s) .and_return(res) get :edit, params: { id: res.id } end it 'assigns @option_array as Array' do expect(assigns(:option_array)).to be_an Array end it 'assigns @option_array with the correct contents' do expect(assigns(:option_array)).to eq([[item.name, item.id]]) end it { is_expected.to render_template(:edit) } end context 'when accessed by checkout person allowed by settings' do before(:each) do mock_app_config(AC_DEFAULTS.merge(checkout_persons_can_edit: true)) mock_user_sign_in(UserMock.new(:checkout_person)) end it_behaves_like 'can access edit page' end context 'when accessed by admin' do before(:each) do mock_user_sign_in(UserMock.new(:admin)) end include_examples 'can access edit page' end end describe '#update (PUT /reservations/:id)' do # Access: everyone who can access GET edit # Functionality: # - assign @reservation # - check due_date > start_date from params; if not, flash error and # redirect back # - if params[:equipment_item] is defined, swap the item from the # current reservation # - affect the current reservation (@reservation) # - set flash notice # - redirect to @reservation # Expects in params: # - params[:equipment_item] = id of equipment item or nil # - params[:reservation] with :start_date, :due_date, :reserver_id, :notes before(:all) do @user = FactoryGirl.create(:user) @checkout_person = FactoryGirl.create(:checkout_person) @admin = FactoryGirl.create(:admin) end after(:all) { User.destroy_all } before(:each) do @reservation = FactoryGirl.create(:valid_reservation, reserver: @user) end it_behaves_like 'inaccessible by banned user' do before { put :update, params: { id: 1 } } end context 'when accessed by patron' do before(:each) do sign_in @user put :update, params: { id: @reservation.id } end include_examples 'redirected request' end context 'when accessed by checkout person disallowed by settings' do before(:each) do sign_in @checkout_person mock_app_config(AC_DEFAULTS.merge(checkout_persons_can_edit: false)) put :update, params: { id: @reservation.id, reservation: FactoryGirl.attributes_for(:reservation) } end include_examples 'redirected request' end ## Happy paths due to authorization shared_examples 'can access update page' do # Happy paths describe 'and provides valid params[:reservation]' do before(:each) do attr = FactoryGirl.attributes_for(:reservation, start_date: Time.zone.today, due_date: Time.zone.today + 4.days) put :update, params: { id: @reservation.id, reservation: attr, equipment_item: '' } end it 'should update the reservation details' do @reservation.reload expect(@reservation.start_date).to eq(Time.zone.today) expect(@reservation.due_date).to eq(Time.zone.today + 4.days) end it 'updates the reservations notes' do expect { @reservation.reload }.to change(@reservation, :notes) end it { is_expected.to redirect_to(@reservation) } end describe 'and provides valid params[:equipment_item]' do before(:each) do @new_equipment_item = FactoryGirl.create(:equipment_item, equipment_model: @reservation.equipment_model) attr = FactoryGirl.attributes_for(:reservation, start_date: Time.zone.today, due_date: (Time.zone.today + 1.day)) put :update, params: { id: @reservation.id, reservation: attr, equipment_item: @new_equipment_item.id } end it 'should update the item on current reservation' do expect { @reservation.reload }.to\ change { @reservation.equipment_item } end it 'should update the item notes' do expect { @new_equipment_item.reload }.to\ change(@new_equipment_item, :notes) end it 'updates the reservations notes' do expect { @reservation.reload }.to change(@reservation, :notes) end it { is_expected.to redirect_to(@reservation) } context 'with existing equipment item' do before(:each) do @old_item = FactoryGirl.create(:equipment_item, equipment_model: @reservation.equipment_model) @new_item = FactoryGirl.create(:equipment_item, equipment_model: @reservation.equipment_model) attr = FactoryGirl.attributes_for(:reservation, start_date: Time.zone.today, due_date: Time.zone.today + 1.day) put :update, params: { id: @reservation.id, reservation: attr, equipment_item: @old_item.id } @old_item.reload @new_item.reload put :update, params: { id: @reservation.id, reservation: attr, equipment_item: @new_item.id } end it 'should update both histories' do expect { @old_item.reload }.to change(@old_item, :notes) expect { @new_item.reload }.to change(@new_item, :notes) end it 'should make the other item available' do @old_item.reload expect(@old_item.status).to eq('available') end end context 'with checked out equipment item' do before(:each) do @old_item = FactoryGirl.create(:equipment_item, equipment_model: @reservation.equipment_model) @new_item = FactoryGirl.create(:equipment_item, equipment_model: @reservation.equipment_model) @other_res = FactoryGirl.create(:reservation, reserver: @user, equipment_model: @reservation.equipment_model) attr = FactoryGirl.attributes_for(:reservation, start_date: Time.zone.today, due_date: Time.zone.today + 1.day) put :update, params: { id: @reservation.id, reservation: attr, equipment_item: @old_item.id } put :update, params: { id: @other_res.id, reservation: attr, equipment_item: @new_item.id } @old_item.reload @new_item.reload put :update, params: { id: @reservation.id, reservation: attr, equipment_item: @new_item.id } end it 'should update both histories' do expect { @old_item.reload }.to change(@old_item, :notes) expect { @new_item.reload }.to change(@new_item, :notes) end it 'should be noted in the other reservation' do expect { @other_res.reload }.to change(@other_res, :notes) end end end # Unhappy path describe 'and provides invalid params[:reservation]' do before(:each) do request.env['HTTP_REFERER'] = reservation_path(@reservation) attr = FactoryGirl.attributes_for(:reservation, start_date: Time.zone.today, due_date: Time.zone.today - 1.day) put :update, params: { id: @reservation.id, reservation: attr, equipment_item: '' } end include_examples 'redirected request' it 'does not update the reservations notes' do expect { @reservation.reload }.not_to change(@reservation, :notes) end end end context 'when accessed by checkout person allowed by settings' do before(:each) do mock_app_config(AC_DEFAULTS.merge(checkout_persons_can_edit: true)) sign_in @checkout_person end include_examples 'can access update page' end context 'when accessed by admin' do before(:each) { sign_in @admin } include_examples 'can access update page' end end describe '#destroy (DELETE /reservations/:id)' do # SMELL: this mostly tests permissions # Special access: # - checkout persons, if checked_out is nil # - users, if checked_out is nil and it's their reservation # Functionality: # - destroy reservation, set flash[:notice], redirect to reservations_url ADMIN_ROLES = %i[admin checkout_person].freeze shared_examples 'can destroy reservation' do before { delete :destroy, params: { id: res.id } } it { is_expected.to redirect_to(reservations_url) } it { is_expected.to set_flash[:notice] } it 'deletes the reservation' do expect(res).to have_received(:destroy) end end shared_examples 'cannot destroy reservation' do before { delete :destroy, params: { id: res.id } } include_examples 'redirected request' end ADMIN_ROLES.each do |role| before { mock_user_sign_in(UserMock.new(role)) } let!(:res) { ReservationMock.new(traits: [:findable]) } it_behaves_like 'can destroy reservation' end context 'when accessed by patron' do let!(:user) { UserMock.new } before { mock_user_sign_in(user) } context 'and the reservation is their own' do context 'and it is checked out' do let!(:res) do ReservationMock.new(traits: [:findable], reserver: user, status: 'checked_out') end it_behaves_like 'cannot destroy reservation' end context 'and it is not checked out' do let!(:res) do ReservationMock.new(traits: [:findable], reserver: user) end it_behaves_like 'can destroy reservation' end end context 'and the reservation is not their own' do let!(:res) { ReservationMock.new(traits: [:findable]) } it_behaves_like 'cannot destroy reservation' end end it_behaves_like 'inaccessible by banned user' do let!(:res) { ReservationMock.new(traits: [:findable]) } before do allow(User).to receive(:find_by_id) delete :destroy, params: { id: res.id } end end end describe '#manage (GET /reservations/manage/:user_id)' do # Access: admins and checkout persons # Functionality: # - assigns @user, @check_out_set and @check_in_set # - renders :manage shared_examples 'can access #manage' do let!(:user) { UserMock.new(traits: [:findable]) } before(:each) do allow(user).to receive(:due_for_checkout) .and_return(instance_spy('ActiveRecord::Relation')) allow(user).to receive(:due_for_checkin) .and_return(instance_spy('ActiveRecord::Relation')) get :manage, params: { user_id: user.id } end it { expect(response).to be_successful } it { is_expected.to render_template(:manage) } it 'assigns @user correctly' do expect(assigns(:user)).to eq(user) end it 'assigns @check_out_set correctly' do expect(assigns(:check_out_set)).to eq(user.due_for_checkout) end it 'assigns @check_in_set correctly' do expect(assigns(:check_in_set)).to eq(user.due_for_checkin) end end context 'when accessed by admin' do before(:each) { mock_user_sign_in(UserMock.new(:admin)) } include_examples 'can access #manage' end context 'when accessed by checkout person' do before(:each) { mock_user_sign_in(UserMock.new(:checkout_person)) } include_examples 'can access #manage' end context 'when accessed by patron' do before(:each) do user = UserMock.new mock_user_sign_in(user) get :manage, params: { user_id: user.id } end include_examples 'redirected request' end end describe '#current (GET /reservations/current/:user_id)' do # not particularily messy but the method is written in a way that # makes mocking + stubbing difficult # SMELL: feature envy: everything depends on @user before(:all) do @user = FactoryGirl.create(:user) @checkout_person = FactoryGirl.create(:checkout_person) @admin = FactoryGirl.create(:admin) @banned = FactoryGirl.create(:banned) end after(:all) do User.destroy_all end shared_examples 'can access #current' do before { get :current, params: { user_id: @user.id } } it { expect(response).to be_successful } it { is_expected.to render_template(:current_reservations) } it 'assigns @user correctly' do expect(assigns(:user)).to eq(@user) end it 'assigns @user_overdue_reservations_set correctly' do expect(assigns(:user_overdue_reservations_set)).to\ eq [Reservation.overdue.for_reserver(@user)].delete_if(&:empty?) end it 'assigns @user_checked_out_today_reservations_set correctly' do expect(assigns(:user_checked_out_today_reservations_set)).to\ eq [Reservation.checked_out_today.for_reserver(@user)] .delete_if(&:empty?) end it 'assigns @user_checked_out_previous_reservations_set correctly' do expect(assigns(:user_checked_out_previous_reservations_set)).to\ eq [Reservation.checked_out_previous.for_reserver(@user)] .delete_if(&:empty?) end it 'assigns @user_reserved_reservations_set correctly' do expect(assigns(:user_reserved_reservations_set)).to\ eq [Reservation.reserved.for_reserver(@user)].delete_if(&:empty?) end end context 'when accessed by admin' do before(:each) do sign_in @admin end include_examples 'can access #current' end context 'when accessed by checkout person' do before(:each) do sign_in @checkout_person end include_examples 'can access #current' end context 'when accessed by patron' do before(:each) do sign_in @user get :current, params: { user_id: @user.id } end include_examples 'redirected request' end it_behaves_like 'inaccessible by banned user' do before { get :current, params: { user_id: @banned.id } } end context 'with banned reserver' do before(:each) do sign_in @admin get :current, params: { user_id: @banned.id } end it 'is a redirect' do expect(response).to be_redirect end it 'sets the flash' do expect(flash[:error]).not_to be_nil end end end describe '#checkout (PUT /reservations/checkout/:user_id)' do # Access: Admins, checkout persons. # Functionality: very complicated (almost 100 lines) # - pass TOS (if not, redirect) # - params[:reservations] contains hash of # {reservation_id => {equipment_item_id: int, notes: str, # checkout_precedures: {checkout_procedure_id => int}}} # - stops checkout if user has overdue reservations # - stops checkout if no reservations are selected # - overrides errors if you can and if there are some, otherwise # redirects away # - also prevents checkout if reserver is banned # Effects if successful: # - sets empty @check_in_set, populates @check_out_set with the # reservations # - processes all reservations in params[:reservations] -- adds # checkout_handler, checked_out (time), equipment_item; updates # notes # - renders :receipt template # - sets reservation status to 'checked_out' # Note: Many of these can be cross-applied to #checkin as well before(:all) do @user = FactoryGirl.create(:user) @checkout_person = FactoryGirl.create(:checkout_person) @admin = FactoryGirl.create(:admin) @banned = FactoryGirl.create(:banned) end after(:all) { User.destroy_all } before(:each) do sign_in @user @reservation = FactoryGirl.create(:valid_reservation, reserver: @user) end shared_examples 'has successful checkout' do before(:each) do @item = FactoryGirl.create(:equipment_item, equipment_model: @reservation.equipment_model) reservations_params = { @reservation.id.to_s => { notes: '', equipment_item_id: @item.id } } ActionMailer::Base.deliveries = [] put :checkout, params: { user_id: @user.id, reservations: reservations_params } end it { expect(response).to be_successful } it { is_expected.to render_template(:receipt) } it 'assigns empty @check_in_set' do expect(assigns(:check_in_set)).to be_empty end it 'populates @check_out_set' do expect(assigns(:check_out_set)).to eq [@reservation] end it 'updates the reservation' do expect(@reservation.checkout_handler).to be_nil expect(@reservation.checked_out).to be_nil expect(@reservation.equipment_item).to be_nil expect(@reservation.reserved?).to be_truthy @reservation.reload expect(@reservation.checkout_handler).to be_a(User) expect(@reservation.checked_out).to_not be_nil expect(@reservation.equipment_item).to eq @item expect(@reservation.checked_out).to be_truthy end it 'updates the equipment item history' do expect { @item.reload }.to change(@item, :notes) end it 'updates the reservation notes' do expect { @reservation.reload }.to change(@reservation, :notes) end it 'sends checkout receipts' do expect(ActionMailer::Base.deliveries.count).to eq(1) end end context 'when accessed by admin' do before(:each) do sign_in @admin end include_examples 'has successful checkout' end context 'when accessed by checkout person' do before(:each) do sign_in @checkout_person end include_examples 'has successful checkout'
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
true
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/controllers/catalog_controller_spec.rb
spec/controllers/catalog_controller_spec.rb
# frozen_string_literal: true require 'spec_helper' describe CatalogController, type: :controller do before(:each) do @app_config = FactoryGirl.create(:app_config) @user = FactoryGirl.create(:user) @cart = FactoryGirl.build(:cart, reserver_id: @user.id) sign_in @user # @controller.stub(:cart).and_return(session[@cart]) # @controller.stub(:fix_cart_date) end describe 'GET index' do before(:each) do # the first hash passed here is params[] and the second is session[] get :index, params: {} # , { cart: @cart } end it 'sets @reserver_id to the current cart.reserver_id' do expect(assigns(:reserver_id)).to eq(@user.id) end it { is_expected.to respond_with(:success) } it { is_expected.to render_template(:index) } it { is_expected.not_to set_flash } end describe 'PUT add_to_cart' do context 'valid equipment_model selected' do before(:each) do @equipment_model = FactoryGirl.create(:equipment_model) put :add_to_cart, params: { id: @equipment_model.id } end it 'should call cart.add_item to add item to cart' do expect do put :add_to_cart, params: { id: @equipment_model.id } end.to change { session[:cart].items[@equipment_model.id] }.by(1) end it 'should set flash[:error] if errors exist' do allow(@cart).to receive(:validate_items).and_return('test') allow(@cart).to receive(:validate_dates_and_items).and_return('test2') expect(flash[:error]).not_to be_nil end it { is_expected.to redirect_to(root_path) } end context 'invalid equipment_model selected' do before(:each) do # there are no equipment models in the db so this is invalid put :add_to_cart, params: { id: 1 } end it { is_expected.to redirect_to(root_path) } it { is_expected.to set_flash } it 'should add logger error' do expect(Rails.logger).to\ receive(:error).with('Attempt to add invalid equipment model 1') # this call has to come after the previous line put :add_to_cart, params: { id: 1 } end end end describe 'POST submit_cart_updates_form on item' do before(:each) do @equipment_model = FactoryGirl.create(:equipment_model) put :add_to_cart, params: { id: @equipment_model.id } end it 'should adjust item quantity' do params = { id: @equipment_model.id, quantity: 2, reserver_id: @user.id } post :submit_cart_updates_form, params: params expect(session[:cart].items[@equipment_model.id]).to eq(2) expect(assigns(:errors)).to eq session[:cart].validate_all is_expected.to redirect_to(new_reservation_path) end it 'should remove item when quantity is 0' do params = { id: @equipment_model.id, quantity: 0, reserver_id: @user.id } post :submit_cart_updates_form, params: params # should remove the item after setting quantity to 0 expect(session[:cart].items).to be_empty is_expected.to redirect_to(root_path) end end describe 'PUT changing dates on confirm reservation page' do before(:each) do @equipment_model = FactoryGirl.create(:equipment_model) put :add_to_cart, params: { id: @equipment_model.id } end it 'should set new dates' do # sets start and due dates to tomorrow and day after tomorrow tomorrow = Time.zone.today + 1.day params = { cart: { start_date_cart: tomorrow.strftime('%Y-%m-%d'), due_date_cart: (tomorrow + 1.day).strftime('%Y-%m-%d') }, reserver_id: @user.id } post :change_reservation_dates, params: params expect(session[:cart].start_date).to eq(tomorrow) expect(session[:cart].due_date).to eq(tomorrow + 1.day) end end describe 'PUT update_user_per_cat_page' do before(:each) do put :update_user_per_cat_page end it 'should set session[:items_per_page] to params[items_per_page] '\ 'if exists' do put :update_user_per_cat_page, params: { items_per_page: 20 } expect(session[:items_per_page]).to eq('20') end it 'should not alter session[:items_per_page] if '\ 'params[:items_per_page] is nil' do session[:items_per_page] = '15' put :update_user_per_cat_page, params: { items_per_page: nil } expect(session[:items_per_page]).not_to eq(nil) expect(session[:items_per_page]).to eq('15') end it { is_expected.to redirect_to(root_path) } end # I don't like that this test is actually searching the database, but # unfortunately I couldn't get the model methods to stub correctly describe 'PUT search' do context 'query is blank' do before(:each) do put :search, params: { query: '' } end it { is_expected.to redirect_to(root_path) } end context 'query is not blank' do it 'should call catalog_search on EquipmentModel and return active '\ 'equipment models' do @equipment_model = FactoryGirl.create(:equipment_model, active: true, description: 'query') # EquipmentModel.stub(:catelog_search).with('query') # .and_return(@equipment_model) put :search, params: { query: 'query' } expect(assigns(:equipment_model_results)).to eq([@equipment_model]) end it 'should give unique results even with multiple matches' do @equipment_model = FactoryGirl.create(:equipment_model, active: true, name: 'query', description: 'query') put :search, params: { query: 'query' } expect(assigns(:equipment_model_results)).to eq([@equipment_model]) expect(assigns(:equipment_model_results).uniq!).to eq(nil) # no dups end it 'should call catalog_search on EquipmentItem' do @equipment_item = FactoryGirl.create(:equipment_item, serial: 'query') # EquipmentItem.stub(:catelog_search).with('query') # .and_return(@equipment_item) put :search, params: { query: 'query' } expect(assigns(:equipment_item_results)).to eq([@equipment_item]) end it 'should call catalog_search on Category' do @category = FactoryGirl.create(:category, name: 'query') # Category.stub(:catelog_search).with('query').and_return(@category) put :search, params: { query: 'query' } expect(assigns(:category_results)).to eq([@category]) end end end context 'application-controller centric tests' do before(:each) do @app_config = FactoryGirl.create(:app_config) # this is to ensure that all before_filters are run @first_user = FactoryGirl.create(:user) @user = FactoryGirl.create(:user) sign_in @user end describe 'app_setup_check' do context 'user and appconfig in the db' do before(:each) do get :index end it { is_expected.to respond_with(:success) } it { is_expected.not_to set_flash } end context 'no app_config' do before(:each) do AppConfig.delete_all get :index end it { is_expected.to set_flash } it { is_expected.to render_template('application_setup/index') } end context 'no user in the db' do before(:each) do sign_out @user User.delete_all get :index end it { is_expected.to set_flash } it { is_expected.to render_template('application_setup/index') } end end describe 'seen_app_configs' do before(:each) do @admin = FactoryGirl.create(:admin) sign_in @admin end context 'app configs have not been viewed' do before(:each) do AppConfig.delete_all @app_config = FactoryGirl.create(:app_config, viewed: false) get :index end it { is_expected.to set_flash } it { is_expected.to respond_with(:redirect) } it { is_expected.to redirect_to(edit_app_configs_path) } end context 'app configs have been viewed' do before(:each) do get :index end it { is_expected.not_to set_flash } it { is_expected.to respond_with(:success) } it { is_expected.not_to redirect_to(edit_app_configs_path) } end end describe 'load_configs' do it 'should set @app_configs to the first AppConfig' do get :index expect(assigns(:app_configs)).to eq(AppConfig.first) end end describe 'cart' do it 'makes a new cart record for session[:cart] if !cart' do get :index expect(session[:cart].is_a?(Cart)).to be_truthy end it 'returns session[:cart] if cart.reserver_id' do session[:cart] = Cart.new session[:cart].reserver_id = @user.id get :index expect(session[:cart].reserver_id).to eq(@user.id) end it 'sets the session[:cart].reserver_id to current_user.id if '\ '!cart.reserver_id && current_user' do session[:cart] = Cart.new get :index expect(session[:cart].reserver_id).to eq(@user.id) end it 'returns session[:cart] without a reserver_id if !cart.reserver_id '\ '&& !current_user' do sign_out @user session[:cart] = Cart.new get :index expect(session[:cart].reserver_id).to be_nil end end describe 'fix_cart_date' do before(:each) do session[:cart] = Cart.new allow(controller).to receive(:cart).and_return(session[:cart]) end it 'changes cart.start_date to today if date is in the past' do session[:cart].start_date = Time.zone.today - 1.day get :index expect(session[:cart].start_date).to eq(Time.zone.today) end it 'does not change the start_date if date is in the future' do session[:cart].start_date = Time.zone.today + 1.day get :index expect(session[:cart].start_date).to eq(Time.zone.today + 1.day) expect(session[:cart].start_date).not_to eq(Time.zone.today) end end end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/controllers/reports_controller_spec.rb
spec/controllers/reports_controller_spec.rb
# frozen_string_literal: true require 'spec_helper' describe ReportsController, type: :controller do before(:all) do @user = FactoryGirl.create(:user) @banned = FactoryGirl.create(:banned) @checkout_person = FactoryGirl.create(:checkout_person) @admin = FactoryGirl.create(:admin) end context 'as admin user' do before(:each) do mock_app_config sign_in @admin end describe 'PUT /reports/update' do it 'defaults to the past year without a session or params' do get :index # set @start_date and @end_date put :update_dates, format: :js expect(assigns(:start_date)).to eq(Time.zone.today - 1.year) expect(assigns(:end_date)).to eq(Time.zone.today) end it 'keeps the session values with no params' do # set @start_date and @end_date to session values get :index, params: {}, session: { report_start_date: Time.zone.today - 2.days, report_end_date: Time.zone.today - 1.day } put :update_dates, params: { format: :js }, session: { report_start_date: Time.zone.today - 2.days, report_end_date: Time.zone.today - 1.day } expect(assigns(:start_date)).to eq(Time.zone.today - 2.days) expect(assigns(:end_date)).to eq(Time.zone.today - 1.day) end it 'changes the dates and session with valid params' do # set @start_date and @end_date to session values get :index, params: {}, session: { report_start_date: Time.zone.today - 2.days, report_end_date: Time.zone.today - 1.day } put :update_dates, params: { format: :js, report: { start_date: Time.zone.today + 1.day, end_date: Time.zone.today + 2.days } }, session: { report_start_date: Time.zone.today - 2.days, report_end_date: Time.zone.today - 1.day } expect(assigns(:start_date)).to eq(Time.zone.today + 1.day) expect(assigns(:end_date)).to eq(Time.zone.today + 2.days) expect(session[:report_start_date]).to eq(Time.zone.today + 1.day) expect(session[:report_end_date]).to eq(Time.zone.today + 2.days) end end end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/controllers/categories_controller_spec.rb
spec/controllers/categories_controller_spec.rb
# frozen_string_literal: true require 'spec_helper' describe CategoriesController, type: :controller do before(:each) { mock_app_config } it_behaves_like 'calendarable', Category describe 'GET index' do context 'user is admin' do before do mock_user_sign_in(UserMock.new(:admin)) get :index end it_behaves_like 'successful request', :index it 'populates an array of active categories' do allow(Category).to receive(:active) get :index expect(Category).to have_received(:active) end context 'show_deleted' do it 'populates an array of all categories' do allow(Category).to receive(:all) get :index, params: { show_deleted: true } expect(Category).to have_received(:all) end end end context 'user is not admin' do before do mock_user_sign_in get :index end it_behaves_like 'redirected request' end end describe 'GET show' do context 'user is admin' do # NOTE: this may be a superfluous test; #show doesn't do much let!(:cat) { CategoryMock.new(traits: [:findable]) } before do mock_user_sign_in(UserMock.new(:admin)) get :show, params: { id: cat.id } end it_behaves_like 'successful request', :show it 'sets category to the selected category' do get :show, params: { id: cat.id } expect(Category).to have_received(:find).with(cat.id.to_s) .at_least(:once) end end context 'user is not admin' do before do mock_user_sign_in get :show, params: { id: 1 } end it_behaves_like 'redirected request' end end describe 'GET new' do context 'user is admin' do before do mock_user_sign_in(UserMock.new(:admin)) get :new end it_behaves_like 'successful request', :new it 'assigns a new category to @category' do expect(assigns(:category)).to be_new_record expect(assigns(:category).is_a?(Category)).to be_truthy end end context 'user is not admin' do before do mock_user_sign_in get :new end it_behaves_like 'redirected request' end end describe 'POST create' do context 'user is admin' do before { mock_user_sign_in(UserMock.new(:admin)) } context 'successful save' do let!(:cat) { FactoryGirl.build_stubbed(:category) } before do allow(Category).to receive(:new).and_return(cat) allow(cat).to receive(:save).and_return(true) post :create, params: { category: { name: 'Name' } } end it { is_expected.to set_flash[:notice] } it { is_expected.to redirect_to(cat) } end context 'unsuccessful save' do let!(:cat) { CategoryMock.new } before do allow(Category).to receive(:new).and_return(cat) allow(cat).to receive(:save).and_return(false) post :create, params: { category: { name: 'Name' } } end it { is_expected.to set_flash[:error] } it { is_expected.to render_template(:new) } end end context 'user is not admin' do before do mock_user_sign_in post :create, params: { category: { name: 'Name' } } end it_behaves_like 'redirected request' end end describe 'PUT update' do context 'is admin' do before { mock_user_sign_in(UserMock.new(:admin)) } context 'successful update' do let!(:cat) { FactoryGirl.build_stubbed(:category) } before do allow(Category).to receive(:find).with(cat.id.to_s).and_return(cat) allow(cat).to receive(:update).and_return(true) attributes_hash = { id: 2 } put :update, params: { id: cat.id, category: attributes_hash } end it { is_expected.to set_flash[:notice] } it { is_expected.to redirect_to(cat) } end context 'unsuccessful update' do let!(:cat) { CategoryMock.new(traits: [:findable]) } before do allow(cat).to receive(:update).and_return(false) put :update, params: { id: cat.id, category: { id: 2 } } end it { is_expected.to render_template(:edit) } end end context 'user is not admin' do before do mock_user_sign_in put :update, params: { id: 1, category: { id: 2 } } end it_behaves_like 'redirected request' end end describe 'PUT deactivate' do context 'is admin' do before { mock_user_sign_in(UserMock.new(:admin)) } shared_examples 'not confirmed' do |flash_type, **opts| let!(:cat) { FactoryGirl.build_stubbed(:category) } before do allow(Category).to receive(:find).with(cat.id.to_s).and_return(cat) allow(cat).to receive(:destroy) put :deactivate, params: { id: cat.id, **opts } end it { is_expected.to set_flash[flash_type] } it { is_expected.to redirect_to(cat) } it "doesn't destroy the category" do expect(cat).not_to have_received(:destroy) end end it_behaves_like 'not confirmed', :notice, deactivation_cancelled: true it_behaves_like 'not confirmed', :error context 'confirmed' do let!(:cat) do CategoryMock.new(traits: [:findable], equipment_models: []) end before do request.env['HTTP_REFERER'] = 'where_i_came_from' put :deactivate, params: { id: cat.id, deactivation_confirmed: true } end it 'destroys the category' do expect(cat).to have_received(:destroy) end end context 'with reservations' do let!(:cat) { CategoryMock.new(traits: [:findable]) } let!(:res) { instance_spy('reservation') } before do model = EquipmentModelMock.new(traits: [[:with_category, cat: cat]]) # stub out scope chain -- SMELL allow(Reservation).to receive(:for_eq_model).with(model.id) .and_return(Reservation) allow(Reservation).to receive(:finalized).and_return([res]) request.env['HTTP_REFERER'] = 'where_i_came_from' put :deactivate, params: { id: cat.id, deactivation_confirmed: true } end it 'archives the reservation' do expect(res).to have_received(:archive) end end end context 'user is not admin' do before do mock_user_sign_in put :deactivate, params: { id: 1 } end it_behaves_like 'redirected request' end end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/models/equipment_model_spec.rb
spec/models/equipment_model_spec.rb
# frozen_string_literal: true require 'spec_helper' describe EquipmentModel, type: :model do it_behaves_like 'linkable' it_behaves_like 'soft deletable' def mock_eq_model(**attrs) FactoryGirl.build_stubbed(:equipment_model, **attrs) end it 'has a working factory' do expect(FactoryGirl.create(:equipment_model)).to be_truthy end describe 'basic validations' do let!(:model) { mock_eq_model } it { is_expected.to have_and_belong_to_many(:requirements) } it { is_expected.to have_many(:equipment_items) } it { is_expected.to have_many(:reservations) } it { is_expected.to have_many(:checkin_procedures) } it { is_expected.to accept_nested_attributes_for(:checkin_procedures) } it { is_expected.to have_many(:checkout_procedures) } it { is_expected.to accept_nested_attributes_for(:checkout_procedures) } it { is_expected.to have_and_belong_to_many(:associated_equipment_models) } it { is_expected.to validate_presence_of(:name) } it { is_expected.to validate_uniqueness_of(:name).case_insensitive } it { is_expected.to validate_presence_of(:description) } it { is_expected.to belong_to(:category) } it 'requires an associated category' do model.category = nil expect(model.valid?).to be_falsey end end describe 'attribute-specific validations' do shared_examples 'integer attribute' do |attr| it 'is valid with an integer value' do model = mock_eq_model(attr => 2) expect(model.valid?).to be_truthy end it 'is not valid with a non integer value' do model = FactoryGirl.build(:equipment_model) model.send("#{attr}=", 2.3) expect(model.valid?).to be_falsey end it 'is not valid when negative' do model = mock_eq_model(attr => -1) expect(model.valid?).to be_falsey end it 'is valid when nil' do model = mock_eq_model(attr => nil) expect(model.valid?).to be_truthy end end shared_examples 'allows 0' do |attr| it 'is valid when 0' do model = mock_eq_model(attr => 0) expect(model.valid?).to be_truthy end end shared_examples 'does not allow 0' do |attr| it 'is not valid when 0' do model = mock_eq_model(attr => 0) expect(model.valid?).to be_falsey end end describe 'max_per_user' do it_behaves_like 'integer attribute', :max_per_user it_behaves_like 'does not allow 0', :max_per_user end describe 'max_renewal_length' do it_behaves_like 'integer attribute', :max_renewal_length it_behaves_like 'allows 0', :max_renewal_length end describe 'max_renewal_times' do it_behaves_like 'integer attribute', :max_renewal_times it_behaves_like 'allows 0', :max_renewal_times end describe 'renewal_days_before_due' do it_behaves_like 'integer attribute', :renewal_days_before_due it_behaves_like 'allows 0', :renewal_days_before_due end shared_examples 'string attribute' do |attr| it 'fails when less than 0' do model = mock_eq_model(attr => '-1.00') expect(model.valid?).to be_falsey end it 'can be 0' do model = mock_eq_model(attr => '0.00') expect(model.valid?).to be_truthy end end describe 'late fee' do it_behaves_like 'string attribute', :late_fee end describe 'replacement fee' do it_behaves_like 'string attribute', :replacement_fee end end describe 'association validations' do let!(:unique_id) { FactoryGirl.generate(:unique_id) } it 'does not permit association with itself' do model = FactoryGirl.create(:equipment_model, id: unique_id) model.associated_equipment_model_ids = [unique_id] expect(model.save).to be_falsey end describe '.not_associated_with_self' do it 'creates an error if associated with self' do model = FactoryGirl.create(:equipment_model, id: unique_id) model.associated_equipment_model_ids = [unique_id] expect { model.not_associated_with_self }.to \ change { model.errors.messages } end end end describe '#catalog_search' do it 'return equipment_models with all of the query words in '\ 'either name or description' do model = FactoryGirl.create(:equipment_model, name: 'Tumblr hipster', description: 'jean shorts') another = FactoryGirl.create(:equipment_model, name: 'Tumblr starbucks', description: 'jean bag') expect(EquipmentModel.catalog_search('Tumblr jean')).to\ eq([model, another]) end it 'does not return any equipment_models without every query word '\ 'in the name or description' do model = FactoryGirl.create(:equipment_model, name: 'Tumblr hipster', description: 'jean shorts') another = FactoryGirl.create(:equipment_model, name: 'Tumblr starbucks', description: 'jean bag') expect(EquipmentModel.catalog_search('starbucks')).to eq([another]) expect(EquipmentModel.catalog_search('Tumblr hipster')).to eq([model]) end end describe 'attribute inheritance methods' do shared_examples 'inherits from category' do |method, attr| it 'returns the value if set' do model = mock_eq_model expect(model.send(method)).to eq(model.send(attr)) end it 'returns the category value if nil' do category = FactoryGirl.build_stubbed(:category) model = mock_eq_model(category: category, attr => nil) expect(model.send(method)).to eq(category.send(method)) end end describe '.maximum_per_user' do it_behaves_like 'inherits from category', :maximum_per_user, :max_per_user end describe '.maximum_renewal_length' do it_behaves_like 'inherits from category', :maximum_renewal_length, :max_renewal_length end describe '.maximum_renewal_times' do it_behaves_like 'inherits from category', :maximum_renewal_times, :max_renewal_times end describe '.maximum_renewal_days_before_due' do it_behaves_like 'inherits from category', :maximum_renewal_days_before_due, :renewal_days_before_due end end describe '.model_restricted?' do it 'returns false if the user has fulfilled the requirements '\ 'to use the model' do req = [FactoryGirl.build_stubbed(:requirement)] user = FactoryGirl.build_stubbed(:user, requirements: req) allow(User).to receive(:find).with(user.id).and_return(user) model = mock_eq_model(requirements: req) expect(model.model_restricted?(user.id)).to be_falsey end it 'returns false if the model has no requirements' do user = FactoryGirl.build_stubbed(:user) allow(User).to receive(:find).with(user.id).and_return(user) model = mock_eq_model expect(model.model_restricted?(user.id)).to be_falsey end it 'returns true if the user has not fulfilled all of the requirements' do req = Array.new(2) { FactoryGirl.build_stubbed(:requirement) } user = FactoryGirl.build_stubbed(:user, requirements: [req.first]) allow(User).to receive(:find).with(user.id).and_return(user) model = mock_eq_model(requirements: req) expect(model.model_restricted?(user.id)).to be_truthy end it 'returns true if the user has not fulfilled any of the requirements' do req = Array.new(2) { FactoryGirl.build_stubbed(:requirement) } user = FactoryGirl.build_stubbed(:user) allow(User).to receive(:find).with(user.id).and_return(user) model = mock_eq_model(requirements: req) expect(model.model_restricted?(user.id)).to be_truthy end end context 'methods involving reservations' do ACTIVE = %i[valid_reservation checked_out_reservation].freeze INACTIVE = %i[checked_in_reservation overdue_returned_reservation missed_reservation request].freeze describe '.num_available' do shared_examples 'overlapping' do |type, start_offset, due_offset| it 'is correct' do model = FactoryGirl.create(:equipment_model) res = FactoryGirl.create(type, equipment_model: model) expect(model.num_available(res.start_date + start_offset, res.due_date + due_offset)).to eq(0) end end shared_examples 'with an active reservation' do |type| it 'is correct with no overlap' do model = FactoryGirl.create(:equipment_model) res = FactoryGirl.create(type, equipment_model: model) expect(model.num_available(res.due_date + 1.day, res.due_date + 2.days)).to eq(1) end it_behaves_like 'overlapping', type, 0.days, 0.days it_behaves_like 'overlapping', type, 1.day, 1.day it_behaves_like 'overlapping', type, -1.days, 1.day end ACTIVE.each { |s| it_behaves_like 'with an active reservation', s } context 'when requests_affect_availability is set' do before { mock_app_config(requests_affect_availability: true) } it_behaves_like 'with an active reservation', :request end context 'with a checked-out, overdue reservation' do it 'is correct with no overlap' do model = FactoryGirl.create(:equipment_model) res = FactoryGirl.create(:overdue_reservation, equipment_model: model) expect(model.num_available(res.due_date + 1.day, res.due_date + 2.days)).to eq(0) end it_behaves_like 'overlapping', :overdue_reservation, 0.days, 0.days it_behaves_like 'overlapping', :overdue_reservation, 1.day, 1.day it_behaves_like 'overlapping', :overdue_reservation, -1.days, 1.day end shared_examples 'with an inactive reservation' do |type| it 'is correct with no overlap' do model = FactoryGirl.create(:equipment_model) res = FactoryGirl.create(type, equipment_model: model) expect(model.num_available(res.due_date + 1.day, res.due_date + 2.days)).to eq(1) end it 'is correct with overlap' do model = FactoryGirl.create(:equipment_model) res = FactoryGirl.create(type, equipment_model: model) expect(model.num_available(res.start_date, res.due_date)).to eq(1) end end INACTIVE.each { |s| it_behaves_like 'with an inactive reservation', s } end describe '.num_available_on' do it 'correctly calculates the number of items available' do model = FactoryGirl.create(:equipment_model) FactoryGirl.create_list(:equipment_item, 4, equipment_model: model) FactoryGirl.create(:valid_reservation, equipment_model: model) FactoryGirl.create(:checked_out_reservation, equipment_model: model) FactoryGirl.create(:overdue_reservation, equipment_model: model) expect(model.num_available_on(Time.zone.today)).to eq(1) end end describe 'destroy' do it 'destroys the model' do model = FactoryGirl.create(:equipment_model) expect(model.destroy).to be_truthy end end describe 'when a photo is attached' do let(:equip_model) { create(:equipment_model) } let(:file) { instance_spy('file') } before do allow(ActiveStorage::Blob).to receive(:service).and_return(file) end it 'attaches photo' do photo_blob = ActiveStorage::Blob.new(content_type: 'image/jpg', filename: 'test.jpg', checksum: 'test', byte_size: 1.byte) expect(equip_model.update(photo_blob: photo_blob)).to be_truthy end it 'does not attach files with wrong filetype' do photo_blob = ActiveStorage::Blob.new(content_type: 'BAD', filename: 'test.jpg', checksum: 'test', byte_size: 1.byte) expect(equip_model.update(photo_blob: photo_blob)).to be_falsey end it 'does not attach files that are too large' do photo_blob = ActiveStorage::Blob.new(content_type: 'image/jpg', filename: 'test.jpg', checksum: 'test', byte_size: 2_000_000.byte) expect(equip_model.update(photo_blob: photo_blob)).to be_falsey end end describe 'when a document is attached' do let(:equip_model) { create(:equipment_model) } let(:file) { instance_spy('file') } before do allow(ActiveStorage::Blob).to receive(:service).and_return(file) end it 'attaches photo' do doc_blob = ActiveStorage::Blob.new(content_type: 'application/pdf', filename: 'test.pdf', checksum: 'test', byte_size: 1.byte) expect(equip_model.update(documentation_blob: doc_blob)).to be_truthy end it 'does not attach files with wrong filetype' do doc_blob = ActiveStorage::Blob.new(content_type: 'BAD', filename: 'test.pdf', checksum: 'test', byte_size: 1.byte) expect(equip_model.update(documentation_blob: doc_blob)).to be_falsey end it 'does not attach files that are too large' do doc_blob = ActiveStorage::Blob.new(content_type: 'application/pdf', filename: 'test.jpg', checksum: 'test', byte_size: 6_000_000.byte) expect(equip_model.update(documentation_blob: doc_blob)).to be_falsey end end end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/models/reservation_spec.rb
spec/models/reservation_spec.rb
# frozen_string_literal: true # rubocop:disable Rails/SkipsModelValidations require 'spec_helper' describe Reservation, type: :model do include ActiveSupport::Testing::TimeHelpers it_behaves_like 'linkable' describe 'counter cache' do context 'newly overdue reservation' do it 'increments when a reservation is marked as overdue' do res = FactoryGirl.create(:checked_out_reservation, start_date: Time.zone.today - 2.days, due_date: Time.zone.today - 1.day) res.update_columns(overdue: false) expect(res.equipment_model).to \ receive(:increment!).with(:overdue_count).once res.update(overdue: true) end end context 'already overdue reservation' do it "updating other attributes doesn't affect the cache" do res = FactoryGirl.create(:overdue_reservation) expect(res.equipment_model).not_to receive(:increment!) res.update_attribute(:notes, 'test') end it 'decrements when checked in' do res = FactoryGirl.create(:overdue_reservation) expect(res.equipment_model).to \ receive(:decrement!).with(:overdue_count).once res.update( FactoryGirl.attributes_for(:overdue_returned_reservation, equipment_model: res.equipment_model) ) end it 'decrements when a reservation is extended' do res = FactoryGirl.create(:overdue_reservation) expect(res.equipment_model).to \ receive(:decrement!).with(:overdue_count).once res.update_attribute(:due_date, Time.zone.today + 1.day) end it 'decrements when an overdue reservation is destroyed' do res = FactoryGirl.create(:overdue_reservation) expect(res.equipment_model).to \ receive(:decrement!).with(:overdue_count).once res.destroy! end end context 'overdue, returned reservation' do it 'only decrements once per reservation' do res = FactoryGirl.create(:overdue_returned_reservation) expect(res.equipment_model).not_to receive(:decrement!) res.update_attribute(:notes, 'test') end end context 'normal checked out reservation' do it "doesn't change when a normal reservation is checked in" do res = FactoryGirl.create(:checked_out_reservation) expect(res.equipment_model).not_to receive(:decrement!) expect(res.equipment_model).not_to receive(:increment!) res.update( FactoryGirl.attributes_for(:checked_in_reservation, equipment_model: res.equipment_model) ) end end end describe 'deletable_missed' do context 'when reservations are set to expire' do it 'collects appropriate reservations' do mock_app_config(res_exp_time: 2) old = FactoryGirl.create(:missed_reservation, start_date: Time.zone.today - 3.days, due_date: Time.zone.today - 2.days) FactoryGirl.create(:missed_reservation, start_date: Time.zone.today - 1.day, due_date: Time.zone.today) expect(Reservation.deletable_missed).to eq([old]) end end context "when reservations don't expire" do it 'returns none' do mock_app_config(res_exp_time: '') FactoryGirl.create(:missed_reservation, start_date: Time.zone.today - 3.days, due_date: Time.zone.today - 2.days) FactoryGirl.create(:missed_reservation, start_date: Time.zone.today - 2.days, due_date: Time.zone.today - 1.day) expect(Reservation.deletable_missed).to be_empty end end end describe 'missed_not_emailed' do it 'collects the appropriate reservations' do not_emailed = FactoryGirl.create(:missed_reservation) FactoryGirl.create(:missed_reservation, flags: Reservation::FLAGS[:missed_email_sent]) expect(Reservation.missed_not_emailed).to eq([not_emailed]) end end describe 'newly_missed' do it 'collects the appropriate reservations' do FactoryGirl.create(:missed_reservation) missed = FactoryGirl.create(:missed_reservation, status: 'reserved') expect(Reservation.newly_missed).to eq([missed]) end end describe 'newly overdue' do it 'collects the appropriate reservations' do FactoryGirl.create(:overdue_reservation) overdue = FactoryGirl.create(:overdue_reservation) overdue.update_columns(overdue: false) expect(Reservation.newly_overdue).to eq([overdue]) end end describe '.number_for' do it 'counts the number that overlap with today' do source = Array.new(2) { ReservationMock.new } source.each do |r| allow(r).to receive(:overlaps_with).with(Time.zone.today) .and_return(true) end expect(described_class.number_for(source)).to eq(2) end it 'counts the number that overlap with a given day' do date = Time.zone.today + 2.days source = Array.new(2) { ReservationMock.new } allow(source.first).to receive(:overlaps_with).with(date).and_return(true) allow(source.last).to receive(:overlaps_with).with(date).and_return(false) expect(described_class.number_for(source, date: date)).to eq(1) end it 'counts according to attribute hash' do attrs = { overdue: false } res = ReservationMock.new described_class.number_for([res], **attrs) expect(res).to have_received(:attrs?).with(**attrs) end end describe '.number_for_date_range' do it 'counts the number of reservations over a date range' do date_range = Time.zone.today..(Time.zone.today + 2.days) source = [] date_range.each do |date| allow(described_class).to receive(:number_for).with(source, date: date) end described_class.number_for_date_range(source, date_range) date_range.each do |date| expect(described_class).to have_received(:number_for) .with(source, date: date) end end end describe '.completed_procedures' do it 'returns an empty array when passed nil' do expect(described_class.completed_procedures(nil)).to eq([]) end it "collects an array of keys that have value '1'" do hash = { collected: '1', not_collected: '0' } expect(described_class.completed_procedures(hash)).to \ eq([:collected, nil]) end end describe '.unique_equipment_items?' do it 'returns false when the set has duplicate items' do set = Array.new(2) { ReservationMock.new(equipment_item_id: 1) } expect(described_class.unique_equipment_items?(set)).to be_falsey end it 'returns true when the set has no duplicate items' do set = Array.new(2) { |i| ReservationMock.new(equipment_item_id: i) } expect(described_class.unique_equipment_items?(set)).to be_truthy end end describe 'custom validations' do context 'start date after due date' do subject(:res) do FactoryGirl.build(:valid_reservation, start_date: Time.zone.today + 3.days, due_date: Time.zone.today) end it { is_expected.not_to be_valid } end context 'has an item of a different model' do subject(:res) do item = FactoryGirl.create(:equipment_item) model = FactoryGirl.create(:equipment_model) FactoryGirl.build(:valid_reservation, equipment_model: model, equipment_item: item) end it { is_expected.not_to be_valid } end describe 'availability validation' do context 'availability issues' do subject(:res) do model = FactoryGirl.create(:equipment_model) allow(model).to receive(:num_available).and_return(0) FactoryGirl.build(:valid_reservation, equipment_model: model) end it { is_expected.not_to be_valid } end end context 'start date is in the past' do subject(:res) do FactoryGirl.build(:valid_reservation, start_date: Time.zone.today - 1.day) end it { is_expected.not_to be_valid } end context 'due date is in the past' do subject(:res) do FactoryGirl.build(:valid_reservation, due_date: Time.zone.today - 1.day) end it { is_expected.not_to be_valid } end context 'reserver is banned' do subject(:res) do user = FactoryGirl.create(:banned) FactoryGirl.build(:valid_reservation, reserver: user) end it { is_expected.not_to be_valid } end end describe 'basic validations' do subject(:reservation) { FactoryGirl.build(:valid_reservation) } it { is_expected.to belong_to(:equipment_model) } it { is_expected.to belong_to(:reserver) } it { is_expected.to belong_to(:equipment_item) } it { is_expected.to belong_to(:checkout_handler) } it { is_expected.to belong_to(:checkin_handler) } it { is_expected.to validate_presence_of(:equipment_model) } end describe '#approved?' do it 'returns false if requested' do res = FactoryGirl.build_stubbed(:request) expect(res.approved?).to be_falsey end it 'returns false if denied' do res = FactoryGirl.build_stubbed(:request, status: 'denied') expect(res.approved?).to be_falsey end it 'returns true if approved' do res = FactoryGirl.build_stubbed(:request, status: 'reserved') expect(res.approved?).to be_truthy end it 'returns false if not a request' do res = FactoryGirl.build_stubbed(:valid_reservation) expect(res.approved?).to be_falsey end end describe '#flagged?' do let!(:res) { FactoryGirl.build_stubbed(:valid_reservation) } it 'returns true when flagged' do res.flag(:request) expect(res.flagged?(:request)).to be_truthy end it 'returns false when not flagged' do expect(res.flagged?(:request)).to be_falsey end it 'returns false when the flag is undefined' do expect(res.flagged?(:garbage_flag)).to be_falsey end end describe '#attrs?' do it 'returns true when all attributes match' do attrs = { overdue: true, status: 'checked_out' } res = FactoryGirl.build_stubbed(:overdue_reservation) expect(res.attrs?(attrs)).to be_truthy end it 'returns false when one attribute does not match' do attrs = { overdue: true, status: 'checked_out' } res = FactoryGirl.build_stubbed(:checked_out_reservation) expect(res.attrs?(attrs)).to be_falsey end end describe '#overlaps_with' do let!(:res) do FactoryGirl.build_stubbed(:valid_reservation, start_date: Time.zone.today, due_date: Time.zone.today + 1.day) end it 'returns true when overlapping with date' do expect(res.overlaps_with(Time.zone.today)).to be_truthy end it 'returns false when not overlapping with date' do expect(res.overlaps_with(Time.zone.today - 1.day)).to be_falsey end end describe '#flag' do let!(:res) { FactoryGirl.build_stubbed(:valid_reservation) } it 'flags the reservation' do expect { res.flag(:request) }.to \ change { res.flagged?(:request) }.from(false).to(true) end it 'does nothing if flag is undefined' do expect { res.flag(:garbage) }.not_to change { res.flags } end it 'does nothing if flag is already set' do res.flag(:request) expect { res.flag(:request) }.not_to change { res.flags } end end describe '#unflag' do let!(:res) { FactoryGirl.build_stubbed(:valid_reservation) } it 'unflags the reservation' do res.flag(:request) expect { res.unflag(:request) }.to \ change { res.flagged?(:request) }.from(true).to(false) end it 'does nothing if flag is undefined' do expect { res.unflag(:garbage) }.not_to change { res.flags } end it 'does nothing if not flagged' do expect { res.unflag(:request) }.not_to change { res.flags } end end describe '.expire!' do let!(:res) do FactoryGirl.build_stubbed(:request).tap do |r| allow(r).to receive(:save) end end it 'updates the status' do expect { res.expire! }.to change { res.status } .from('requested').to('denied') end it 'flags as expired' do expect { res.expire! }.to change { res.flagged?(:expired) } .from(false).to(true) end it 'saves the result' do res.expire! expect(res).to have_received(:save) end end describe '#human_status' do shared_examples 'returns the proper string' do |string, type, **attrs| it do res = FactoryGirl.build_stubbed(type, **attrs) expect(res.human_status).to eq(string) end end it_behaves_like 'returns the proper string', 'starts today', :valid_reservation, start_date: Time.zone.today it_behaves_like 'returns the proper string', 'reserved', :valid_reservation, start_date: Time.zone.today + 1.day it_behaves_like 'returns the proper string', 'due today', :checked_out_reservation, due_date: Time.zone.today it_behaves_like 'returns the proper string', 'checked_out', :checked_out_reservation, due_date: Time.zone.today + 1.day it_behaves_like 'returns the proper string', 'returned overdue', :overdue_returned_reservation it_behaves_like 'returns the proper string', 'overdue', :overdue_reservation it_behaves_like 'returns the proper string', 'missed', :missed_reservation it_behaves_like 'returns the proper string', 'returned', :checked_in_reservation it_behaves_like 'returns the proper string', 'requested', :request it_behaves_like 'returns the proper string', 'denied', :request, status: 'denied' end describe '#end_date' do context 'if checked in' do it 'returns the checkin date' do res = FactoryGirl.build_stubbed(:checked_in_reservation) expect(res.end_date).to eq(res.checked_in) end it 'does not care if overdue' do res = FactoryGirl.build_stubbed(:overdue_returned_reservation) expect(res.end_date).to eq(res.checked_in) end end it 'returns today if actively overdue' do res = FactoryGirl.build_stubbed(:overdue_reservation) expect(res.end_date).to eq(Time.zone.today) end it 'returns due date for request' do res = FactoryGirl.build_stubbed(:request) expect(res.end_date).to eq(res.due_date) end it 'returns due date for reserved' do res = FactoryGirl.build_stubbed(:valid_reservation) expect(res.end_date).to eq(res.due_date) end end describe '#duration' do it 'returns the length of the reservation' do res = FactoryGirl.build_stubbed(:valid_reservation, start_date: Time.zone.today, due_date: Time.zone.today + 1.day) length = 2 expect(res.duration).to eq(length) end end describe '#time_checked_out' do it 'returns the length of the checkout for returned reservations' do res = FactoryGirl.build_stubbed(:checked_in_reservation, start_date: Time.zone.today - 3.days, due_date: Time.zone.today - 1.day, checked_out: Time.zone.today - 3.days, checked_in: Time.zone.today - 2.days) length = 2 expect(res.time_checked_out).to eq(length) end end describe '#late_fee' do it 'returns the correct late fee' do fee_per_day = 5 days = 3 expected = fee_per_day * days model = FactoryGirl.build_stubbed(:equipment_model, late_fee: fee_per_day) res = FactoryGirl.build_stubbed(:overdue_reservation, equipment_model: model, due_date: Time.zone.today - days.days) expect(res.late_fee).to eq(expected) end it 'returns 0 if not overdue' do res = FactoryGirl.build_stubbed(:checked_out_reservation) expect(res.late_fee).to eq(0) end it 'returns the cap if a cap is set' do fee_per_day = 5 days = 3 cap = 10 model = FactoryGirl.build_stubbed(:equipment_model, late_fee: fee_per_day, late_fee_max: cap) res = FactoryGirl.build_stubbed(:overdue_reservation, equipment_model: model, due_date: Time.zone.today - days.days) expect(res.late_fee).to eq(cap) end end describe '#reserver' do it 'returns the associated user' do user = FactoryGirl.create(:user) res = FactoryGirl.build_stubbed(:valid_reservation, reserver_id: user.id) expect(res.reserver).to eq(user) end it "returns a dummy user if there isn't one" do res = FactoryGirl.build_stubbed(:valid_reservation, reserver_id: nil) expect(res.reserver).to be_new_record end end describe '#find_renewal_date' do let!(:length) { 5 } let!(:model) do FactoryGirl.create(:equipment_model_with_item, max_renewal_length: length) end let!(:res) do FactoryGirl.build_stubbed(:valid_reservation, reserver: FactoryGirl.create(:user), equipment_model: model) end it 'sets the correct renewal length' do expect(res.find_renewal_date).to eq(res.due_date + length.days) end context 'with a blackout date overlapping with the max renewal length' do it 'sets the correct renewal length' do FactoryGirl.create(:blackout, start_date: res.due_date + 2.days, end_date: res.due_date + length.days + 1.day) expect(res.find_renewal_date).to eq(res.due_date + 1.day) end end context 'with a blackout date going right up to the max renewal length' do it 'sets a length of 0' do FactoryGirl.create(:blackout, start_date: res.due_date + 1.day, end_date: res.due_date + length.days + 1.day) expect(res.find_renewal_date).to eq(res.due_date) end end context 'with a future reservation on the same model' do it 'sets the correct renewal length' do FactoryGirl.create(:reservation, equipment_model: model, start_date: res.due_date + 3.days, due_date: res.due_date + length.days + 1.day) expect(res.find_renewal_date).to eq(res.due_date + 2.days) end end end describe '#eligible_for_renew?' do shared_examples 'not checked out' do |type| it 'returns false' do expect(FactoryGirl.build_stubbed(type).eligible_for_renew?).to be_falsey end end %i[valid_reservation checked_in_reservation request].each do |type| it_behaves_like 'not checked out', type end it 'returns false when overdue' do res = FactoryGirl.build_stubbed(:overdue_reservation) expect(res.eligible_for_renew?).to be_falsey end it 'returns false when the reserver is banned' do user = FactoryGirl.create(:banned) res = FactoryGirl.build_stubbed(:checked_out_reservation, reserver: user) expect(res.eligible_for_renew?).to be_falsey end it 'returns false when the model cannot be renewed' do model = FactoryGirl.build_stubbed(:equipment_model, max_renewal_length: 0) res = FactoryGirl.build_stubbed(:checked_out_reservation, equipment_model: model) expect(res.eligible_for_renew?).to be_falsey end it 'returns false when there are no items available' do model = FactoryGirl.build_stubbed(:equipment_model) res = FactoryGirl.build_stubbed(:checked_out_reservation, equipment_model: model) allow(model).to receive(:num_available_on).with(res.due_date + 1.day) .and_return(0) expect(res.eligible_for_renew?).to be_falsey end it 'returns false when renewed more than the max allowed times' do model = FactoryGirl.build_stubbed(:equipment_model) res = FactoryGirl.build_stubbed(:checked_out_reservation, equipment_model: model, times_renewed: 1) allow(model).to receive(:num_available_on).with(res.due_date + 1.day) .and_return(1) allow(model).to receive(:maximum_renewal_times).and_return(1) expect(res.eligible_for_renew?).to be_falsey end it 'returns false before the eligible period' do model = FactoryGirl.build_stubbed(:equipment_model) res = FactoryGirl.build_stubbed(:checked_out_reservation, equipment_model: model, due_date: Time.zone.today + 2.days) allow(model).to receive(:num_available_on).with(res.due_date + 1.day) .and_return(1) allow(model).to receive(:maximum_renewal_times).and_return(1) allow(model).to receive(:maximum_renewal_days_before_due).and_return(1) expect(res.eligible_for_renew?).to be_falsey end it 'returns true when eligible' do model = FactoryGirl.build_stubbed(:equipment_model) res = FactoryGirl.build_stubbed(:checked_out_reservation, equipment_model: model, due_date: Time.zone.today + 2.days) allow(model).to receive(:num_available_on).with(res.due_date + 1.day) .and_return(1) allow(model).to receive(:maximum_renewal_times).and_return(1) allow(model).to receive(:maximum_renewal_days_before_due).and_return(3) expect(res.eligible_for_renew?).to be_truthy end end describe '#to_cart' do it 'returns a new cart object corresponding to the reservation' do res = FactoryGirl.build_stubbed(:valid_reservation, reserver: FactoryGirl.create(:user)) cart = res.to_cart expect(cart).to be_kind_of(Cart) expect(cart.start_date).to eq(res.start_date) expect(cart.due_date).to eq(res.due_date) expect(cart.reserver_id).to eq(res.reserver.id) expect(cart.items).to eq(res.equipment_model_id => 1) end end describe '#renew' do let!(:user) { FactoryGirl.build_stubbed(:user) } it "doesn't renew if ineligible" do res = FactoryGirl.build_stubbed(:valid_reservation) allow(res).to receive(:eligible_for_renew?).and_return(false) expect(res.renew(user)).to match(/not eligible/) end context 'eligible for renew' do let!(:res) do FactoryGirl.build_stubbed(:valid_reservation, times_renewed: 0, notes: '') end let!(:new_date) { Time.zone.today + 5.days } before do allow(res).to receive(:eligible_for_renew?).and_return(true) allow(res).to receive(:find_renewal_date).and_return(new_date) allow(res).to receive(:save) end it 'updates the due date' do old_date = res.due_date expect { res.renew(user) }.to change { res.due_date } .from(old_date).to(new_date) end it 'increments times_renewed' do expect { res.renew(user) }.to change { res.times_renewed }.by(1) end it 'updates the notes' do time_string = Time.zone.now.to_s(:long) due_date_string = new_date.to_s(:long) allow(user).to receive(:md_link).and_return('md link') res.renew(user) expect(res.notes).to match(time_string) expect(res.notes).to match(due_date_string) expect(res.notes).to match(/md link/) expect(res.notes).to match(/Renewed/) end it 'returns nil when successful' do allow(res).to receive(:save).and_return(true) expect(res.renew(user)).to be_nil end it 'returns error if unsuccessful' do allow(res).to receive(:save).and_return(false) expect(res.renew(user)).to be_kind_of(String) end end end describe '#checkin' do let!(:handler) { FactoryGirl.build_stubbed(:checkout_person) } context 'no procedures' do let!(:res) { FactoryGirl.build_stubbed(:checked_out_reservation) } let(:procedures) { instance_spy(ActionController::Parameters, to_h: {}) } it 'sets the checkin handler' do expect { res.checkin(handler, procedures, '') }.to \ change { res.checkin_handler }.from(nil).to(handler) end it 'sets the checked in time' do # travel in order to freeze the time travel(-1.days) do expect { res.checkin(handler, procedures, '') }.to \ change { res.checked_in }.from(nil).to(Time.zone.now) end end it 'sets the status to returned' do expect { res.checkin(handler, procedures, '') }.to \ change { res.status }.from('checked_out').to('returned') end it 'updates the notes' do # FIXME: might fall under overtesting (testing messages sent to self) # but notes handling will be handled by a separate module in the future # alternatively just test that the notes change? # also applies to the next two tests new_notes = '' procedures = instance_spy(ActionController::Parameters, to_h: {}) allow(res).to receive(:make_notes) .with('Checked in', new_notes, [], handler) res.checkin(handler, procedures, new_notes) expect(res).to have_received(:make_notes) .with('Checked in', new_notes, [], handler) end it 'returns the reservation' do expect(res.checkin(handler, procedures, '')).to eq(res) end end context 'with completed procedures' do it 'sends no procedures to the notes' do # FIXME: this part of the method is really in need of refactoring procedure = FactoryGirl.create(:checkin_procedure) model = EquipmentModel.find(procedure.equipment_model.id) res = FactoryGirl.build_stubbed(:checked_out_reservation, equipment_model: model) p_hash = { procedure.id.to_s => '1' } procedures = instance_spy(ActionController::Parameters, to_h: p_hash) allow(res).to receive(:make_notes).with('Checked in', '', [], handler) res.checkin(handler, procedures, '') expect(res).to have_received(:make_notes) .with('Checked in', '', [], handler) end end context 'with incomplete procedures' do it 'sends the incomplete procedures to the notes' do # FIXME: this part of the method is really in need of refactoring procedure = FactoryGirl.create(:checkin_procedure) model = EquipmentModel.find(procedure.equipment_model.id) res = FactoryGirl.build_stubbed(:checked_out_reservation, equipment_model: model) procedures = instance_spy(ActionController::Parameters, to_h: {}) incomplete = [procedure.step] allow(res).to receive(:make_notes) .with('Checked in', '', incomplete, handler) res.checkin(handler, procedures, '') expect(res).to have_received(:make_notes) .with('Checked in', '', incomplete, handler) end end context 'overdue' do let!(:res) { FactoryGirl.create(:overdue_reservation) } let(:procedures) { instance_spy(ActionController::Parameters, to_h: {}) } before do ActionMailer::Base.perform_deliveries = false mock_app_config(admin_email: 'admin@email.com', disable_user_emails: false) end after do ActionMailer::Base.perform_deliveries = true end it 'sends the admins an email' do expect(AdminMailer).to \ receive_message_chain(:overdue_checked_in_fine_admin, :deliver_now) res.checkin(handler, procedures, '') end it 'sends the user an email' do expect(UserMailer).to \ receive_message_chain(:reservation_status_update, :deliver_now) res.checkin(handler, procedures, '') end end end describe '#checkout' do let!(:handler) { FactoryGirl.build_stubbed(:checkout_person) } context 'no procedures' do let!(:model) { FactoryGirl.build_stubbed(:equipment_model) } let!(:res) do FactoryGirl.build_stubbed(:valid_reservation, equipment_model: model) end let!(:item) do FactoryGirl.build_stubbed(:equipment_item, equipment_model: model) end let(:procedures) { instance_spy(ActionController::Parameters, to_h: {}) } it 'sets the checkout handler' do expect { res.checkout(item.id, handler, procedures, '') }.to \ change { res.checkout_handler }.from(nil).to(handler) end it 'sets the checked out time' do # travel in order to freeze the time travel(-1.days) do expect { res.checkout(item.id, handler, procedures, '') }.to \ change { res.checked_out }.from(nil).to(Time.zone.now) end end it 'sets the status to checked_out' do expect { res.checkout(item.id, handler, procedures, '') }.to \ change { res.status }.from('reserved').to('checked_out') end it 'assigns the item' do expect { res.checkout(item.id, handler, procedures, '') }.to \ change { res.equipment_item_id }.from(nil).to(item.id) end it 'updates the notes' do # FIXME: might fall under overtesting (testing messages sent to self) # but notes handling will be handled by a separate module in the future # alternatively just test that the notes change? # also applies to the next two tests new_notes = '' procedures = instance_spy(ActionController::Parameters, to_h: {}) allow(res).to receive(:make_notes) .with('Checked out', new_notes, [], handler) res.checkout(item, handler, procedures, new_notes) expect(res).to have_received(:make_notes) .with('Checked out', new_notes, [], handler) end it 'returns the reservation' do expect(res.checkout(item, handler, procedures, '')).to eq(res) end end context 'with completed procedures' do it 'sends no procedures to the notes' do # FIXME: this part of the method is really in need of refactoring procedure = FactoryGirl.create(:checkout_procedure) model = EquipmentModel.find(procedure.equipment_model.id) item = FactoryGirl.build_stubbed(:equipment_item, equipment_model: model) res = FactoryGirl.build_stubbed(:valid_reservation, equipment_model: model) p_hash = { procedure.id.to_s => '1' } procedures = instance_spy(ActionController::Parameters, to_h: p_hash) allow(res).to receive(:make_notes).with('Checked out', '', [], handler) res.checkout(item, handler, procedures, '') expect(res).to have_received(:make_notes) .with('Checked out', '', [], handler) end end context 'with incomplete procedures' do it 'sends the incomplete procedures to the notes' do # FIXME: this part of the method is really in need of refactoring procedure = FactoryGirl.create(:checkout_procedure) model = EquipmentModel.find(procedure.equipment_model.id) item = FactoryGirl.build_stubbed(:equipment_item, equipment_model: model) res = FactoryGirl.build_stubbed(:valid_reservation, equipment_model: model) procedures = instance_spy(ActionController::Parameters, to_h: {})
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
true
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/models/requirement_spec.rb
spec/models/requirement_spec.rb
# frozen_string_literal: true require 'spec_helper' describe Requirement, type: :model do context 'Validations' do before(:each) do @requirement = FactoryGirl.build(:requirement) end it 'has a working factory' do expect(@requirement.save).to be_truthy end it { is_expected.to validate_presence_of(:contact_name) } it { is_expected.to validate_presence_of(:description) } it { is_expected.to validate_presence_of(:contact_info) } it { is_expected.to have_and_belong_to_many(:equipment_models) } it { is_expected.to have_and_belong_to_many(:users) } end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/models/category_spec.rb
spec/models/category_spec.rb
# frozen_string_literal: true require 'spec_helper' describe Category, type: :model do it_behaves_like 'soft deletable' before(:each) do @category = FactoryGirl.build(:category) end it { is_expected.to validate_presence_of(:name) } it { is_expected.to validate_uniqueness_of(:name).case_insensitive } it { is_expected.to have_many(:equipment_models) } # validate numericality for :max_renewal_length, :max_renewal_times, # :renewal_days_before_due, :max_per_user, :sort_order, :max_checkout_length # this includes integer_only, and greater_than_or_equal_to => 0 # :max_renewal_length it 'validates max_renewal_length must be non-negative' do @category.max_renewal_length = -1 expect(@category.save).to be_falsey @category.max_renewal_length = 0 expect(@category.save).to be_truthy end it 'validates max_renewal_length can be nil' do @category.max_renewal_length = nil expect(@category.save).to be_truthy end it 'validates max_renewal_length must be an integer' do @category.max_renewal_length = 'not_an_integer' expect(@category.save).to be_falsey @category.max_renewal_length = 1 expect(@category.save).to be_truthy end # :max_renewal_times it 'validates max_renewal_times must be non-negative' do @category.max_renewal_times = -1 expect(@category.save).to be_falsey @category.max_renewal_times = 0 expect(@category.save).to be_truthy end it 'validates max_renewal_times can be nil' do @category.max_renewal_times = nil expect(@category.save).to be_truthy end it 'validates max_renewal_times must be an integer' do @category.max_renewal_times = 'not_an_integer' expect(@category.save).to be_falsey @category.max_renewal_times = 1 expect(@category.save).to be_truthy end # :renewal_days_before_due it 'validates renewal_days_before_due must be non-negative' do @category.renewal_days_before_due = -1 expect(@category.save).to be_falsey @category.renewal_days_before_due = 0 expect(@category.save).to be_truthy end it 'validates renewal_days_before_due can be nil' do @category.renewal_days_before_due = nil expect(@category.save).to be_truthy end it 'validates renewal_days_before_due must be an integer' do @category.renewal_days_before_due = 'not_an_integer' expect(@category.save).to be_falsey @category.renewal_days_before_due = 1 expect(@category.save).to be_truthy end # :sort_order it 'validates sort_order must be non-negative' do @category.sort_order = -1 expect(@category.save).to be_falsey @category.sort_order = 0 expect(@category.save).to be_truthy end it 'validates sort_order can be nil' do @category.sort_order = nil expect(@category.save).to be_truthy end it 'validates sort_order must be an integer' do @category.sort_order = 'not_an_integer' expect(@category.save).to be_falsey @category.sort_order = 1 expect(@category.save).to be_truthy end # :max_per_user it 'validates max_per_user must be non-negative' do @category.max_per_user = -1 expect(@category.save).to be_falsey @category.max_per_user = 0 expect(@category.save).to be_truthy end it 'validates max_per_user can be nil' do @category.max_per_user = nil expect(@category.save).to be_truthy end it 'validates max_per_user must be an integer' do @category.max_per_user = 'not_an_integer' expect(@category.save).to be_falsey @category.max_per_user = 1 expect(@category.save).to be_truthy end # :max_checkout_length it 'validates max_checkout_length must be non-negative' do @category.max_checkout_length = -1 expect(@category.save).to be_falsey @category.max_checkout_length = 0 expect(@category.save).to be_truthy end it 'validates max_checkout_length can be nil' do @category.max_checkout_length = nil expect(@category.save).to be_truthy end it 'validates max_checkout_length must be an integer' do @category.max_checkout_length = 'not_an_integer' expect(@category.save).to be_falsey @category.max_checkout_length = 1 expect(@category.save).to be_truthy end # custom scope to return active categories describe '.active' do before(:each) do @deactivated = FactoryGirl.create(:category, deleted_at: '2013-01-01 00:00:00') @category.save end it 'Should return all active categories' do expect(Category.active).to include(@category) end it 'Should not return inactive categories' do expect(Category.active).not_to include(@deactivated) end end describe '#maximum_per_user' do before(:each) do @category.max_per_user = 1 @category.save @unrestrected_category = FactoryGirl.create(:category, max_per_user: nil) end it 'Should return maximum_per_user if defined' do expect(@category.maximum_per_user).to eq(1) end it 'Should return Float::INFINITY if not defined' do expect(@unrestrected_category.maximum_per_user).to eq(Float::INFINITY) end end describe '#maximum_renewal_length' do before(:each) do @category.max_renewal_length = 5 @category.save @unrestrected_category = FactoryGirl.create(:category, max_renewal_length: nil) end it 'Should return maximum_renewal_length if defined' do expect(@category.maximum_renewal_length).to eq(5) end it 'Default to 0 if not defined' do expect(@unrestrected_category.maximum_renewal_length).to eq(0) end end describe '#maximum_renewal_times' do before(:each) do @category.max_renewal_times = 1 @category.save @unrestrected_category = FactoryGirl.create(:category, max_renewal_times: nil) end it 'Should return maximum_renewal_times if defined' do expect(@category.maximum_renewal_times).to eq(1) end it 'Default to infinity if not defined' do expect(@unrestrected_category.maximum_renewal_times).to\ eq(Float::INFINITY) end end describe '#maximum_renewal_days_before_due' do before(:each) do @category.renewal_days_before_due = 1 @category.save @unrestrected_category = FactoryGirl.create(:category, renewal_days_before_due: nil) end it 'Should return maximum_renewal_days_before_due if defined' do expect(@category.maximum_renewal_days_before_due).to eq(1) end it 'Default to infinity if not defined' do expect(@unrestrected_category.maximum_renewal_days_before_due).to\ eq(Float::INFINITY) end end describe '#maximum_checkout_length' do before(:each) do @category.max_checkout_length = 5 @category.save @unrestrected_category = FactoryGirl.create(:category, max_checkout_length: nil) end it 'Should return maximum_checkout_length if defined' do expect(@category.maximum_checkout_length).to eq(5) end it 'Default to infinity if not defined' do expect(@unrestrected_category.maximum_checkout_length).to\ eq(Float::INFINITY) end end describe '.catalog_search' do before(:each) do @category.name = 'Tumblr hipster instagram sustainable' @category.save @hipster = FactoryGirl.create(:category, name: 'Tumblr starbucks PBR slackline music hipster') end it 'Should return names matching all of the query words' do expect(Category.catalog_search('Tumblr')).to eq([@category, @hipster]) expect(Category.catalog_search('Tumblr hipster')).to\ eq([@category, @hipster]) end it 'Should not return any categories without every query word in the '\ 'name' do expect(Category.catalog_search('starbucks')).to eq([@hipster]) expect(Category.catalog_search('Tumblr instagram sustainable')).to\ eq([@category]) end end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/models/announcement_spec.rb
spec/models/announcement_spec.rb
# frozen_string_literal: true require 'spec_helper' describe Announcement, type: :model do # pending "add some examples to (or delete) #{__FILE__}" it 'has current scope' do _passed = Announcement.create! starts_at: Time.zone.today - 2.days, ends_at: Time.zone.today - 1.day, message: 'MyText' _current = Announcement.create! starts_at: Time.zone.today - 1.day, ends_at: Time.zone.today + 1.day, message: 'MyText' _upcoming = Announcement.create! starts_at: Time.zone.today + 1.day, ends_at: Time.zone.today + 2.days, message: 'MyText' end it 'does not include ids passed in to current' do current1 = Announcement.create! starts_at: Time.zone.today - 1.day, ends_at: Time.zone.today + 1.day, message: 'MyText' current2 = Announcement.create! starts_at: Time.zone.today - 1.day, ends_at: Time.zone.today + 1.day, message: 'MyText' expect(Announcement.current([current2.id])).to eq([current1]) end it 'includes current when nil is passed in' do current = Announcement.create! starts_at: Time.zone.today - 1.day, ends_at: Time.zone.today + 1.day, message: 'MyText' expect(Announcement.current(nil)).to eq([current]) end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/models/cart_spec.rb
spec/models/cart_spec.rb
# frozen_string_literal: true require 'spec_helper' describe Cart, type: :model do before(:each) do @cart = FactoryGirl.build(:cart) @cart.items = {} # Needed to avoid db flushing problems end it 'has a working factory' do expect(@cart).to be_valid end context 'General validations' do it { is_expected.to validate_presence_of(:reserver_id) } it { is_expected.to validate_presence_of(:start_date) } it { is_expected.to validate_presence_of(:due_date) } end describe '.initialize' do it 'has no items' do @cart.items.nil? end it 'starts today ' do @cart.start_date == Time.zone.today end it 'is due tomorrow' do @cart.due_date == Time.zone.today + 1.day end it 'has no reserver' do @cart.reserver_id.nil? end it 'has errors' do @cart.errors.count > 0 end end describe '.persisted?' do it { expect(@cart.persisted?).to be_falsey } end describe 'Item handling' do before(:each) do @equipment_model = FactoryGirl.create(:equipment_model) end describe '.add_item' do it 'adds an item' do @cart.add_item(@equipment_model) expect(@cart.items).to include(@equipment_model.id) end it 'increments if an item is already present' do @cart.add_item(@equipment_model) @cart.add_item(@equipment_model) expect(@cart.items[@equipment_model.id]).to eq(2) end end end describe 'Cart actions' do describe '.purge_all' do it 'should empty the items hash' do @cart.purge_all expect(@cart.items).to be_empty end end describe '.prepare_all' do before(:each) do @equipment_model = FactoryGirl.create(:equipment_model) @cart.add_item(@equipment_model) @cart.add_item(@equipment_model) @equipment_model2 = FactoryGirl.create(:equipment_model) @cart.add_item(@equipment_model2) @cart.start_date = Time.zone.today @cart.due_date = Time.zone.today + 1.day @cart.reserver_id = FactoryGirl.create(:user).id end it 'should create an array of reservations' do expect(@cart.prepare_all.class).to eq(Array) expect(@cart.prepare_all.first.class).to eq(Reservation) end describe 'the reservations' do it 'should have the correct dates' do array = @cart.prepare_all array.each do |r| expect(r.start_date).to eq(Time.zone.today) expect(r.due_date).to eq(Time.zone.today + 1.day) end end it 'should have the correct equipment models' do array = @cart.prepare_all expect(@cart.items).to include(array[1].equipment_model.id) expect(@cart.items).to include(array[0].equipment_model.id) expect(@cart.items).to include(array[2].equipment_model.id) end it 'should have the correct reserver ids' do array = @cart.prepare_all array.each do |r| expect(r.reserver_id).to eq @cart.reserver_id end end end end end describe 'Aliases' do describe '.duration' do it 'should calculate the sum correctly' do expect(@cart.duration).to eq(@cart.due_date - @cart.start_date + 1) end end describe '.reserver' do it 'should return a correct user instance' do expect(@cart.reserver).to eq(User.find(@cart.reserver_id)) end end end describe '.empty?' do it 'is true when there are no items in cart' do @cart.items = [] expect(@cart.empty?).to be_truthy end it 'is false when there are some items in cart' do @cart.add_item(FactoryGirl.create(:equipment_model)) expect(@cart.empty?).to be_falsey end end describe 'fix_items' do it 'removes meaningless items' do @em = FactoryGirl.create(:equipment_model) @cart.add_item(@em) @em.destroy(:force) expect { @cart.fix_items }.to change { @cart.items.length }.by(-1) end end describe 'check_availability' do before(:each) do @em = FactoryGirl.create(:equipment_model) FactoryGirl.create(:equipment_item, equipment_model: @em) @cart.add_item(@em) end shared_examples 'validates availability' do |offset| before do @start_date = @cart.start_date - offset @due_date = @cart.due_date + offset end it 'fails if there is a reserved reservation for that model' do FactoryGirl.build(:reservation, equipment_model: @em, start_date: @start_date, due_date: @due_date) .save(validate: false) expect(@cart.check_availability).not_to eq([]) expect(@cart.validate_all).not_to eq([]) end it 'fails if there is a checked out reservation for that model' do FactoryGirl.build(:checked_out_reservation, equipment_model: @em, start_date: @start_date, due_date: @due_date, equipment_item: @em.equipment_items.first) .save(validate: false) expect(@cart.check_availability).not_to eq([]) expect(@cart.validate_all).not_to eq([]) end end it 'passes if there are equipment items available' do expect(@cart.check_availability).to eq([]) end it_behaves_like 'validates availability', 0.days it_behaves_like 'validates availability', 1.day end describe 'check_consecutive' do before(:each) do @em = FactoryGirl.create(:equipment_model) FactoryGirl.create_pair(:equipment_item, equipment_model: @em) @cart.add_item(@em) end shared_examples 'with a consecutive reservation' do |res_type| before do @em.update(max_per_user: 1, max_checkout_length: 3) @res = FactoryGirl.create(res_type, reserver: User.find_by(id: @cart.reserver.id), equipment_model: @em, start_date: @cart.due_date + 1, due_date: @cart.due_date + 2) end it 'fails when the reservation is before' do # rubocop:disable Rails/SkipsModelValidations @res.update_columns(start_date: @cart.start_date - 2, due_date: @cart.start_date - 1) # rubocop:enable Rails/SkipsModelValidations expect(@cart.check_consecutive).not_to eq([]) expect(@cart.validate_all).not_to eq([]) end it 'fails when the reservation is after' do expect(@cart.check_consecutive).not_to eq([]) expect(@cart.validate_all).not_to eq([]) end it 'fails when there are reservations before and after' do @em.update(max_checkout_length: 5) FactoryGirl.build(res_type, reserver: User.find_by(id: @cart.reserver.id), equipment_model: @em, start_date: @cart.start_date - 2, due_date: @cart.start_date - 1).save(validate: false) expect(@cart.check_consecutive).not_to eq([]) expect(@cart.validate_all).not_to eq([]) end it 'passes when checking a renewal' do expect(@cart.check_consecutive).not_to eq([]) expect(@cart.validate_all(true)).to eq([]) end it "passes when max_per_user isn't 1" do @em.update(max_per_user: 5) expect(@em.max_per_user).not_to eq(1) expect(@cart.check_consecutive).to eq([]) end it "passes when it doesn't exceed the max_checkout_length" do @em.update(max_checkout_length: 5) expect(@em.max_checkout_length).to eq(5) expect(@cart.check_consecutive).to eq([]) end end it 'passes without a consecutive reservation' do expect(@cart.check_consecutive).to eq([]) end it_behaves_like 'with a consecutive reservation', :valid_reservation it_behaves_like 'with a consecutive reservation', :checked_out_reservation end describe 'check_max_ems' do before(:each) do @em = FactoryGirl.create(:equipment_model, max_per_user: 1) FactoryGirl.create_pair(:equipment_item, equipment_model: @em) @cart.add_item(@em) end it "passes when the reserver doesn't exceed the item limit" do expect(@cart.check_max_ems).to eq([]) end it 'passes when the cart contains multiple models' do em2 = FactoryGirl.create(:equipment_model, max_per_user: 1) FactoryGirl.create_pair(:equipment_item, equipment_model: em2) @cart.add_item(em2) expect(@cart.check_max_ems).to eq([]) end it 'fails when the reserver exceeds the item limit' do FactoryGirl.create(:valid_reservation, reserver: User.find_by(id: @cart.reserver_id), equipment_model: @em) expect(@cart.check_max_ems).not_to eq([]) end it 'fails when the reserver exceeds the item limit with an overdue res' do FactoryGirl.create(:overdue_reservation, reserver: User.find_by(id: @cart.reserver_id), equipment_model: @em) expect(@cart.check_max_ems).not_to eq([]) end context 'reserver has unrelated reservation' do it 'passes' do other_em = FactoryGirl.create(:equipment_model) reserver = User.find(@cart.reserver_id) FactoryGirl.create(:valid_reservation, reserver: reserver, equipment_model: other_em) expect(@cart.check_max_ems).to be_empty end end end describe 'check_max_cat' do before(:each) do @cat = FactoryGirl.create(:category, max_per_user: 1) @ems = FactoryGirl.create_pair(:equipment_model, category: @cat) @ems.each do |em| FactoryGirl.create_pair(:equipment_item, equipment_model: em) end @cart.add_item(@ems.first) end it "passes when the reserver doesn't exceed the item limit" do expect(@cart.check_max_cat).to eq([]) end it 'passes when the cart has items from multiple categories' do cat2 = FactoryGirl.create(:category, max_per_user: 1) em3 = FactoryGirl.create(:equipment_model, category: cat2) FactoryGirl.create_pair(:equipment_item, equipment_model: em3) @cart.add_item(em3) expect(@cart.check_max_cat).to eq([]) end it 'fails when the reserver exceeds the item limit' do FactoryGirl.create(:valid_reservation, reserver: User.find_by(id: @cart.reserver_id), equipment_model: @ems.last) expect(@cart.check_max_cat).not_to eq([]) end it 'fails when the reserver exceeds the item limit with an overdue res' do FactoryGirl.create(:overdue_reservation, reserver: User.find_by(id: @cart.reserver_id), equipment_model: @ems.last) expect(@cart.check_max_cat).not_to eq([]) end context 'reserver has unrelated reservation' do it 'passes' do other_cat = FactoryGirl.create(:equipment_model, category: FactoryGirl.create(:category)) reserver = User.find(@cart.reserver_id) FactoryGirl.create(:valid_reservation, reserver: reserver, equipment_model: other_cat) expect(@cart.check_max_cat).to be_empty end end end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/models/checkout_procedure_spec.rb
spec/models/checkout_procedure_spec.rb
# frozen_string_literal: true require 'spec_helper' describe CheckoutProcedure, type: :model do it_behaves_like 'soft deletable' it { is_expected.to belong_to(:equipment_model) } end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/models/message_spec.rb
spec/models/message_spec.rb
# frozen_string_literal: true require 'spec_helper' describe Message, type: :model do context 'validations' do it { is_expected.to validate_presence_of(:name) } it { is_expected.to validate_presence_of(:email) } it { is_expected.to validate_presence_of(:subject) } it { is_expected.to validate_presence_of(:body) } it do is_expected.not_to\ allow_value('abc', '!s@abc.com', 'a@!d.com').for(:email) end it do is_expected.to\ allow_value('example@example.com', '1a@a.edu', 'a@2a.net').for(:email) end # this test currently fails but I'm not sure why # also, why would we want to be able to leave email blank? # it 'should skip email format validation if input is nil or an empty '\ # 'string' do # @message = FactoryGirl.build(:message, email: '') # @message.should be_valid # end end describe '.persisted?' do it 'should always return false' do @message = FactoryGirl.build(:message) expect(@message.persisted?).to be_falsey end end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/models/report_spec.rb
spec/models/report_spec.rb
# frozen_string_literal: true require 'spec_helper' describe Report, type: :model do before(:each) do @report = Report.new end describe Report::Column do it 'can be constructed from arrays' do column = Report::Column.arr_to_col ['Name', :scope, :type, :field] expect(column.name).to eq('Name') expect(column.filter).to eq(:scope) expect(column.data_type).to eq(:type) expect(column.data_field).to eq(:field) end end describe Report::Row do it 'can be constructed from Equipment Models' do em = FactoryGirl.create(:equipment_model) row = Report::Row.item_to_row em expect(row.name).to eq(em.name) expect(row.item_id).to eq(em.id) expect(row.link_path).to eq(Rails.application.routes.url_helpers .subreport_path(id: em.id, class: 'equipment_model')) end it 'can be constructed from Reservations' do u = FactoryGirl.build(:reservation) u.save(validate: false) row = Report::Row.item_to_row u expect(row.name).to eq(u.name) expect(row.item_id).to eq(u.id) expect(row.link_path).to eq(Rails.application.routes.url_helpers .reservation_path(id: u.id)) end end describe '.average2' do it 'returns N/A for arrays of size 0' do expect(Report.average2([])).to eq('N/A') end it 'returns N/A for arrays consisting of nil' do expect(Report.average2([nil, nil])).to eq('N/A') end it 'calculates averages correctly' do expect(Report.average2([1, 2, 3])).to eq(2) end it 'throws out nils' do expect(Report.average2([1, 2, 3, nil])).to eq(2) end it 'rounds to 2 decimal places' do expect(Report.average2([0.12, 1.799, 4.3])).to eq(2.07) end end describe '.get_class' do it 'converts equipment_item_id to EquipmentItem' do expect(Report.get_class(:equipment_item_id)).to eq(EquipmentItem) end it 'works on :reserver_id' do expect(Report.get_class(:reserver_id)).to eq(User) end it 'returns Reservation when given :id' do expect(Report.get_class(:id)).to eq(Reservation) end end describe '.build_new' do DEFAULT_COLUMNS = [['Total', :all, :count], ['Reserved', :reserved, :count], ['Checked Out', :checked_out, :count], ['Overdue', :overdue, :count], ['Returned On Time', :returned_on_time, :count], ['Returned Overdue', :returned_overdue, :count], ['User Count', :all, :count, :reserver_id]].freeze before(:each) do @id = :equipment_item_id @class = EquipmentItem @report = Report.build_new(@id) end it 'returns a report object' do expect(@report.class).to eq(Report) end it 'sets the row_item_type' do expect(@report.row_item_type).to eq(@id) end it 'has the correctly headed columns' do @report.columns.each_with_index do |col, i| col.name = DEFAULT_COLUMNS[i][0] col.filter = DEFAULT_COLUMNS[i][1] col.data_type = DEFAULT_COLUMNS[i][2] col.data_field = DEFAULT_COLUMNS[i][3] end end it 's columns res_sets have the correct number of elements' do @report.columns.each_with_index do |col, _i| expect(col.res_set.count).to eq Reservation.send(col.filter).count end end it 's columns res_sets are of type array' do # important that they're not AR:Relation for speed purposes @report.columns.each do |col| expect(col.res_set.class).to eq Array end end it 's columns res_sets are just ids under the right circumstances' do @report.columns.each_with_index do |col, _i| next unless col.data_field.nil? && col.data_type == :count expect(col.res_set).to eq(Reservation.send(col.filter) .collect(&@id)) end end it 'has the correctly headed rows' do items = @class.all items.each do |item| expect(@report.rows).to include?(Report::Row.item_to_row(item)) end end end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/models/blackout_spec.rb
spec/models/blackout_spec.rb
# frozen_string_literal: true require 'spec_helper' describe Blackout, type: :model do context 'validations and associations' do it { is_expected.to validate_presence_of(:notice) } it { is_expected.to validate_presence_of(:start_date) } it { is_expected.to validate_presence_of(:end_date) } it { is_expected.to validate_presence_of(:blackout_type) } it 'validates a set_id if it is a recurring blackout' # new feature that should exist already end describe 'get_notices_for_date' do before do @soft = FactoryGirl.create(:blackout, blackout_type: 'soft', notice: 'soft_notice') @hard = FactoryGirl.create(:blackout) @other_soft = FactoryGirl.create(:blackout, start_date: (Time.zone.today + 3.days), blackout_type: 'soft', notice: 'other notice') @other_hard = FactoryGirl.create(:blackout, start_date: (Time.zone.today + 3.days), notice: 'other notice again') end after(:all) do Blackout.delete_all end context 'all blackouts' do subject(:return_value) do Blackout.get_notices_for_date(Time.zone.today) end it 'should contain the soft notice' do expect(return_value).to include(@soft.notice) end it 'should contain the hard notice' do expect(return_value).to include(@hard.notice) end it 'should not contain the other notices' do expect(return_value).to_not include(@other_soft.notice) expect(return_value).to_not include(@other_hard.notice) end end context 'only hard blackouts' do subject(:return_value) do Blackout.get_notices_for_date(Time.zone.today, :hard) end it 'should contain the hard notice' do expect(return_value).to include(@hard.notice) end it 'should not contain any other notices' do expect(return_value).to_not include(@soft.notice) expect(return_value).to_not include(@other_soft.notice) expect(return_value).to_not include(@other_hard.notice) end end context 'only soft blackouts' do subject(:return_value) do Blackout.get_notices_for_date(Time.zone.today, :soft) end it 'should contain the soft notice' do expect(return_value).to include(@soft.notice) end it 'should not contain any other notices' do expect(return_value).to_not include(@hard.notice) expect(return_value).to_not include(@other_soft.notice) expect(return_value).to_not include(@other_hard.notice) end end end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/models/checkin_procedure_spec.rb
spec/models/checkin_procedure_spec.rb
# frozen_string_literal: true require 'spec_helper' describe CheckinProcedure, type: :model do it_behaves_like 'soft deletable' it { is_expected.to belong_to(:equipment_model) } end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/models/app_config_spec.rb
spec/models/app_config_spec.rb
# frozen_string_literal: true require 'spec_helper' describe AppConfig, type: :model do before(:all) { AppConfig.delete_all } before(:each) { @ac = FactoryGirl.build(:app_config) } it 'has a working factory' do expect(@ac.save).to be_truthy end it 'does not accept empty site title' do @ac.site_title = nil expect(@ac).not_to be_valid @ac.site_title = ' ' expect(@ac).not_to be_valid end it 'does not accept too long a site title' do @ac.site_title = 'AaaaaBbbbbCccccDddddEeeee' expect(@ac).not_to be_valid end it "shouldn't have an invalid e-mail" do emails = ['ana@com', 'anda@pres,com', nil, ' '] emails.each do |invalid| @ac.admin_email = invalid expect(@ac).not_to be_valid end end it 'should have a valid and present e-mail' do @ac.admin_email = 'ana@yale.edu' expect(@ac).to be_valid end it "shouldn't have an invalid contact e-mail" do emails = ['ana@com', 'anda@pres,com'] emails.each do |invalid| @ac.contact_link_location = invalid expect(@ac).not_to be_valid end end it 'accepts favicon' do file = instance_spy('file') allow(ActiveStorage::Blob).to receive(:service).and_return(file) favicon = ActiveStorage::Blob.new(content_type: 'image/vnd.microsoft.icon', filename: 'test.jpg', checksum: 'test', byte_size: 1.byte) expect(@ac.update(favicon_blob: favicon)).to be_truthy end it 'does not accept favicon with wrong filetype' do file = instance_spy('file') allow(ActiveStorage::Blob).to receive(:service).and_return(file) favicon = ActiveStorage::Blob.new(content_type: 'image/jpg', filename: 'test.jpg', checksum: 'test', byte_size: 1.byte) expect(@ac.update(favicon_blob: favicon)).to be_falsey end context '.contact_email' do it 'returns the contact e-mail if it is set' do @ac.contact_link_location = 'contact@example.com' @ac.save expect(AppConfig.contact_email).to eq('contact@example.com') AppConfig.delete_all end it 'returns the admin e-mail if no contact e-mail is set' do @ac.contact_link_location = '' @ac.save expect(AppConfig.contact_email).to eq(AppConfig.check(:admin_email)) AppConfig.delete_all end end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/models/equipment_item_spec.rb
spec/models/equipment_item_spec.rb
# frozen_string_literal: true require 'spec_helper' describe EquipmentItem, type: :model do include ActiveSupport::Testing::TimeHelpers it_behaves_like 'linkable' it_behaves_like 'soft deletable' describe 'basic validations' do subject(:item) { FactoryGirl.build(:equipment_item) } it { is_expected.to validate_presence_of(:name) } it { is_expected.to validate_presence_of(:equipment_model) } end describe 'serial' do it 'can be blank' do item = FactoryGirl.build_stubbed(:equipment_item, serial: '') expect(item.valid?).to be_truthy end it 'can be nil' do item = FactoryGirl.build_stubbed(:equipment_item, serial: nil) expect(item.valid?).to be_truthy end it 'cannot be the same as another item of the same model' do model = FactoryGirl.create(:equipment_model) FactoryGirl.create(:equipment_item, equipment_model: model, serial: 'a') item = FactoryGirl.build(:equipment_item, equipment_model: model, serial: 'a') expect(item.valid?).to be_falsey end it 'can be the same as another item of a different model' do FactoryGirl.create(:equipment_item, serial: 'a', equipment_model: FactoryGirl.create(:equipment_model)) item = FactoryGirl.build(:equipment_item, serial: 'a', equipment_model: FactoryGirl.create(:equipment_model)) expect(item.valid?).to be_truthy end end it 'saves an empty string value as nil for deleted_at field' do # this test passes even without the nilify_blanks call in the model, maybe # delete the call? item = FactoryGirl.build(:equipment_item) item.deleted_at = ' ' item.save expect(item.deleted_at).to eq(nil) end describe '#active' do it 'returns active equipment items' do active = FactoryGirl.create(:equipment_item) FactoryGirl.create(:deactivated_item) expect(described_class.active).to match_array([active]) end end describe '#for_eq_model' do it 'counts the number of items for the given model' do items = Array.new(2) { |i| EquipmentItemMock.new(equipment_model_id: i) } expect(described_class.for_eq_model(0, items)).to eq(1) end end describe '#status' do it "returns 'Deactivated' when deleted_at is set" do item = FactoryGirl.build_stubbed(:equipment_item, deleted_at: Time.zone.today) expect(item.status).to eq('Deactivated') end it "returns 'available' when active and not currently checked out" do item = FactoryGirl.build_stubbed(:equipment_item) expect(item.status).to eq('available') end it 'includes reservation information when checked out' do res = FactoryGirl.create(:checked_out_reservation) item = res.equipment_item expect(item.status).to include('checked out by') end it 'includes deactivation reason if it is set' do reason = 'because i can' item = FactoryGirl.build_stubbed(:equipment_item, deleted_at: Time.zone.today, deactivation_reason: reason) expect(item.status).to include(reason) end end describe '#current_reservation' do it 'returns nil if no associated reservation' do item = FactoryGirl.build_stubbed(:equipment_item) expect(item.current_reservation).to be_nil end it 'returns the reservation that currently has the item checked out' do res = FactoryGirl.create(:checked_out_reservation) item = res.equipment_item expect(item.current_reservation).to eq(res) end end describe '#available?' do it 'returns true when the status is available' do item = FactoryGirl.build_stubbed(:equipment_item) expect(item.available?).to be_truthy end it 'returns false if when the status is not available' do item = FactoryGirl.build_stubbed(:equipment_item) allow(item).to receive(:status).and_return('not') expect(item.available?).to be_falsey end end describe '#make_reservation_notes' do let!(:user) { UserMock.new(md_link: 'md_link') } let!(:item) { FactoryGirl.build(:equipment_item) } it 'updates the notes' do allow(item).to receive(:update) item.make_reservation_notes('', ReservationMock.new(reserver: user), user, '', Time.zone.now) expect(item).to have_received(:update) .with(hash_including(:notes)) end it 'includes the given time' do time = Time.zone.now item.make_reservation_notes('', ReservationMock.new(reserver: user), user, '', time) expect(item.notes).to include(time.to_s(:long)) end it 'includes the current user link' do item.make_reservation_notes('', ReservationMock.new(reserver: UserMock.new), user, '', Time.zone.now) expect(item.notes).to include(user.md_link) end it 'includes the reservation link' do res = ReservationMock.new(reserver: UserMock.new, md_link: 'res_link') item.make_reservation_notes('', res, user, '', Time.zone.now) expect(item.notes).to include(res.md_link) end it 'includes the reserver link' do reserver = UserMock.new(md_link: 'reserver_link') res = ReservationMock.new(reserver: reserver) item.make_reservation_notes('', res, user, '', Time.zone.now) expect(item.notes).to include(reserver.md_link) end it 'includes extra notes' do item.make_reservation_notes('', ReservationMock.new(reserver: UserMock.new), user, 'extra_note', Time.zone.now) expect(item.notes).to include('extra_note') end end describe '#make_switch_notes' do let!(:user) { UserMock.new } let!(:item) { FactoryGirl.build(:equipment_item) } it 'updates the notes' do allow(item).to receive(:update) item.make_switch_notes(nil, nil, user) expect(item).to have_received(:update) .with(hash_including(:notes)) end it 'includes the reservation links when passed' do old = ReservationMock.new(md_link: 'old_link') new = ReservationMock.new(md_link: 'new_link') item.make_switch_notes(old, new, user) expect(item.notes).to include(old.md_link) expect(item.notes).to include(new.md_link) end it 'includes the current time' do travel(-1.days) do time = Time.zone.now.to_s(:long) item.make_switch_notes(nil, nil, user) expect(item.notes).to include(time) end end it 'includes the handler link' do allow(user).to receive(:md_link).and_return('user_link') item.make_switch_notes(nil, nil, user) expect(item.notes).to include(user.md_link) end end describe '#update' do let!(:user) { UserMock.new } context 'no changes' do let!(:item) { FactoryGirl.build_stubbed(:equipment_item) } it 'does nothing' do expect { item.update_equipment_item(user, {}) }.not_to change { item.notes } end end context 'any changes' do let!(:item) { FactoryGirl.build_stubbed(:equipment_item) } it 'includes the current time' do travel(-1.days) do time = Time.zone.now.to_s(:long) item.update_equipment_item(user, serial: 'a') expect(item.notes).to include(time) end end it 'includes the current user' do allow(user).to receive(:md_link).and_return('user_link') item.update_equipment_item(user, serial: 'a') expect(item.notes).to include(user.md_link) end end shared_examples 'string change noted' do |attr| it do old_value = 'a' new_value = 'b' item = FactoryGirl.build_stubbed(:equipment_item, attr => old_value) item.update_equipment_item(user, attr => new_value) expect(item.notes).to include(old_value) expect(item.notes).to include(new_value) end end it_behaves_like 'string change noted', :name it_behaves_like 'string change noted', :serial context 'changing the equipment model' do it 'notes the change' do old_model = FactoryGirl.create(:equipment_model) new_model = FactoryGirl.create(:equipment_model) item = FactoryGirl.build_stubbed(:equipment_item, equipment_model: old_model) item.update_equipment_item(user, equipment_model_id: new_model.id) expect(item.notes).to include('Equipment Model') expect(item.notes).to include(old_model.name) expect(item.notes).to include(new_model.name) end end end describe '#deactivate' do let!(:user) { UserMock.new(md_link: 'md_link') } let!(:item) { FactoryGirl.build_stubbed(:equipment_item) } before do allow(item).to receive(:destroy) allow(item).to receive(:save!) end context 'with user and notes' do it 'saves the updated attributes' do item.deactivate(user: user, reason: 'reason') expect(item).to have_received(:save!) end it 'destroys the item' do item.deactivate(user: user, reason: 'reason') expect(item).to have_received(:destroy) end it 'prepends to the notes' do item.deactivate(user: user, reason: 'reason') expect(item.notes).to include('reason') expect(item.notes).to include(user.md_link) end end context 'without user' do it 'does nothing' do expect { item.deactivate(reason: 'reason') }.not_to change { item } end end context 'without notes' do it 'does nothing' do expect { item.deactivate(user: user) }.not_to change { item } end end context 'without parameters' do it 'does nothing' do expect { item.deactivate }.not_to change { item } end end end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/models/user_spec.rb
spec/models/user_spec.rb
# frozen_string_literal: true require 'spec_helper' include EnvHelpers describe User, type: :model do it 'has a working factory' do expect(FactoryGirl.create(:user)).to be_valid end context 'validations and associations' do before(:each) do @user = FactoryGirl.create(:user) end it { is_expected.to have_many(:reservations) } it { is_expected.to have_and_belong_to_many(:requirements) } it { is_expected.to validate_presence_of(:username) } it { is_expected.to validate_uniqueness_of(:username).case_insensitive } it { is_expected.to validate_presence_of(:first_name) } it { is_expected.to validate_presence_of(:last_name) } it { is_expected.to validate_presence_of(:affiliation) } it { is_expected.to validate_presence_of(:email) } it do is_expected.not_to \ allow_value('abc', '!s@abc.com', 'a@!d.com').for(:email) end it do is_expected.to \ allow_value('example@example.com', '1a@a.edu', 'a@2a.net').for(:email) end # These tests are commented because currently, the app does not validate # phone unless that option is specifically requested by the admin. This # needs to be expanded in order to test all admin options in app config. # it { should validate_presence_of(:phone) } # it { should_not allow_value("abcdef", "555-555-55$5").for(:phone) } # it { should allow_value("555-555-5555", "15555555555").for(:phone) } it { is_expected.not_to allow_value('ab@', 'ab1', 'ab_c').for(:nickname) } it { is_expected.to allow_value(nil, '', 'abc', 'Example').for(:nickname) } # TODO: figure out why it's saving with terms_of_service_accepted = false it 'must accept ToS' do # @user.terms_of_service_accepted = nil # @user.save.should be_nil @user.terms_of_service_accepted = true expect(@user.save).to be_truthy end # this test means nothing if the previous one fails it "doesn't have to accept ToS if created by an admin" do @user_made_by_admin = FactoryGirl.build(:user, created_by_admin: true, terms_of_service_accepted: false) expect(@user_made_by_admin.save).to be_truthy end end describe '#nickname' do before(:each) do @user = FactoryGirl.create(:user) end it 'should default to empty string' do expect(@user.nickname).to eq('') end it 'should not allow nil' do @user.nickname = nil expect(->() { @user.save }).to\ raise_error(ActiveRecord::StatementInvalid) # User.find(@user.id).nickname.should_not be_nil # this test fails, saying that user nickname # cannot be nil so...idk what is going on end end describe '.active' do before(:each) do @user = FactoryGirl.create(:user) @deactivated = FactoryGirl.create(:banned) end it 'should return all active users' do expect(User.active).to include(@user) end it 'should not return inactive users' do expect(User.active).not_to include(@deactivated) end end describe '#name' do it 'should return the nickname and last name joined into one string if '\ 'nickname is specified' do @user = FactoryGirl.create(:user, nickname: 'Sasha Fierce') expect(@user.name).to eq("#{@user.nickname} #{@user.last_name}") end it 'should return the first and last name if user has no nickname '\ 'specified' do @no_nickname = FactoryGirl.create(:user) expect(@no_nickname.name).to\ eq("#{@no_nickname.first_name} #{@no_nickname.last_name}") end end describe '#equipment_items' do it 'has a working reservation factory' do @reservation = FactoryGirl.create(:valid_reservation) end it 'should return all equipment_items reserved by the user' do @user = FactoryGirl.create(:user) @reservation = FactoryGirl.create(:valid_reservation, reserver: @user) expect(@user.equipment_items).to eq([@reservation.equipment_item]) end end # TODO: find a way to simulate an ldap database using a test fixture/factory # of some kind, esp now that we have both LDAP and API functionality describe '.search' do xit 'should return a hash of user attributes if the ldap database has the '\ 'login associated with user' xit 'should return nil if the user is not in the ldap database' end describe '.select_options' do it 'should return an array of all users ordered by last name, each '\ "represented by an array like this: ['first_name last_name', id]" do @user1 = FactoryGirl.create(:user, first_name: 'Joseph', last_name: 'Smith', nickname: 'Joe') @user2 = FactoryGirl.create(:user, first_name: 'Jessica', last_name: 'Greene', nickname: 'Jess') expect(User.select_options).to\ eq([["#{@user2.last_name}, #{@user2.first_name}", @user2.id], ["#{@user1.last_name}, #{@user1.first_name}", @user1.id]]) end end describe '#render_name' do it 'should return the nickname, last name, and username id as a string '\ 'if nickname exists and if using CAS' do env_wrapper('CAS_AUTH' => '1') do @user = FactoryGirl.create(:user, nickname: 'Sasha Fierce') expect(@user.render_name).to\ eq("#{@user.nickname} #{@user.last_name} #{@user.username}") end end it 'should return the first name, last name, and username id as a '\ 'string if no nickname and if using CAS' do env_wrapper('CAS_AUTH' => '1') do @no_nickname = FactoryGirl.create(:user) expect(@no_nickname.render_name).to\ eq("#{@no_nickname.first_name} #{@no_nickname.last_name} "\ "#{@no_nickname.username}") end end it 'should return the nickname and last name as a string if nickname '\ 'exists and not using CAS' do env_wrapper('CAS_AUTH' => nil) do @user = FactoryGirl.create(:user, nickname: 'Sasha Fierce') expect(@user.render_name).to eq("#{@user.nickname} #{@user.last_name}") end end it 'should return the first name and last name as a string if no '\ 'nickname and not using CAS' do env_wrapper('CAS_AUTH' => nil) do @no_nickname = FactoryGirl.create(:user) expect(@no_nickname.render_name).to\ eq("#{@no_nickname.first_name} #{@no_nickname.last_name}") end end end it_behaves_like 'linkable' end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/features/flash_spec.rb
spec/features/flash_spec.rb
# frozen_string_literal: true require 'spec_helper' describe 'Flashes' do context 'when impersonating another user role' do before do FactoryGirl.build(:admin) sign_in_as_user(@admin) visit root_path end it 'has a link to the documentation' do click_on('Patron') expect(page).to have_link('here', href: 'https://yalestc.github.io/reservations/') end it 'has a link to where you revert the view' do click_on('Patron') expect(page).to have_link('below', href: '#view_as') end end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/features/eq_model_editing_spec.rb
spec/features/eq_model_editing_spec.rb
# frozen_string_literal: true require 'spec_helper' describe 'Equipment Model editing', type: :feature do let(:eq_model) { FactoryGirl.create(:equipment_model) } before { sign_in_as_user(@admin) } after { sign_out } it 'works for checkout procedures', js: true do visit edit_equipment_model_path(eq_model) find_link('Add Step', match: :first).click task_input = 'input[id^="equipment_model_checkout_procedures_attributes_"]'\ '[id$="_step"]' find(task_input, match: :first).set('Checkout Task 1') click_on 'Update Equipment model' expect(page).to have_content('Checkout Task 1') end it 'works for checkin procedures', js: true do visit edit_equipment_model_path(eq_model) all(:link, 'Add Step').last.click task_input = 'input[id^="equipment_model_checkin_procedures_attributes_"]'\ '[id$="_step"]' find(task_input, match: :first).set('Checkin Task 1') click_on 'Update Equipment model' expect(page).to have_content('Checkin Task 1') end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/features/import_users_spec.rb
spec/features/import_users_spec.rb
# frozen_string_literal: true require 'spec_helper' describe 'Import Users', type: :feature do before do sign_in_as_user(@admin) create(:user, username: 'BANME') create(:user, username: 'ME2') end it 'can bulk ban users given only usernames' do visit csv_import_page_url attach_users_to_ban_csv check 'overwrite' select 'Banned Users', from: 'user_type' click_on 'Import Users' expect(page).to have_content('Users successfully imported') end def attach_users_to_ban_csv file_path = Rails.root + 'spec/fixtures/users_to_ban.csv' attach_file('csv_upload', file_path) end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/features/task_buttons_spec.rb
spec/features/task_buttons_spec.rb
# frozen_string_literal: true require 'spec_helper' describe 'Rake task buttons', type: :feature do before do sign_in_as_user FactoryGirl.create(:superuser) # The following is necessary to "undo" a stub / mock called for all feature # specs that was designed to avoid weird issues with persistent AppConfig # settings across tests. In principle, we shouldn't really be using mock # data in feature specs, but rather than try to fix all specs we're going to # just make sure that for these specs we get an actual AppConfig object so # that the form renders correctly. For reference, the stub occurs in # spec/support/app_config_helpers.rb, called in # spec/support/feature_helpers.rb. FactoryGirl.create(:app_config).tap do |ac| allow(AppConfig).to receive(:first).and_return(ac) end end it 'works for daily tasks' do visit root_path click_on 'Settings' click_on 'Run Daily Tasks' expect(page).to have_css('.alert-success', text: /Daily tasks queued and running/) end it 'works for hourly tasks' do visit root_path click_on 'Settings' click_on 'Run Hourly Tasks' expect(page).to have_css('.alert-success', text: /Hourly tasks queued and running/) end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/features/receipt_spec.rb
spec/features/receipt_spec.rb
# frozen_string_literal: true require 'spec_helper' describe 'Reservation receipts' do before do # Necessary to override our mocked AppConfig allow(AppConfig.first).to receive(:disable_user_emails).and_return(false) sign_in_as_user @admin end context 'when checked out' do let(:reservation) { FactoryGirl.create(:checked_out_reservation) } it 'sends check out receipts' do visit reservation_path(reservation) click_on 'Email checkout receipt' expect(page).to have_css('.alert-success', text: /Successfully delivered receipt email./) end it 'sends the right e-mail' do visit reservation_path(reservation) click_on 'Email checkout receipt' email = ActionMailer::Base.deliveries.last expect(email.subject).to match(/.+Checked Out$/) end end context 'when checked in' do let(:reservation) { FactoryGirl.create(:checked_in_reservation) } it 'sends check in receipts' do visit reservation_path(reservation) click_on 'Email return receipt' expect(page).to have_css('.alert-success', text: /Successfully delivered receipt email./) end it 'sends the right e-mail' do visit reservation_path(reservation) click_on 'Email return receipt' email = ActionMailer::Base.deliveries.last expect(email.subject).to match(/.+Returned$/) end end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/features/eq_model_deactivation_spec.rb
spec/features/eq_model_deactivation_spec.rb
# frozen_string_literal: true require 'spec_helper' describe 'Equipment Model deactivation', type: :feature do let(:eq_model) { FactoryGirl.create(:equipment_model) } before do FactoryGirl.create(:equipment_item, equipment_model: eq_model) end after { sign_out } shared_examples 'success' do it 'can deactivate and reactivate', js: true do visit equipment_model_path(eq_model) click_link 'Deactivate', href: "/equipment_models/#{eq_model.id}/deactivate" click_link 'Activate', href: "/equipment_models/#{eq_model.id}/activate" expect(page).to have_css('.alert.alert-success', text: /Successfully reactivated/) end end shared_examples 'unauthorized' do it 'cannot deactivate' do visit equipment_model_path(eq_model) expect(page).not_to have_link 'Deactivate' end end context 'as superuser' do before { sign_in_as_user @superuser } it_behaves_like 'success' end context 'as admin' do before { sign_in_as_user @admin } it_behaves_like 'success' end context 'as checkout person' do before { sign_in_as_user @checkout_person } it_behaves_like 'unauthorized' end context 'as patron' do before { sign_in_as_user @user } it_behaves_like 'unauthorized' end context 'as guest' do it_behaves_like 'unauthorized' end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/features/eq_model_spec.rb
spec/features/eq_model_spec.rb
# frozen_string_literal: true require 'spec_helper' describe 'Equipment Model views', type: :feature do context 'show view' do # for pending reservations before(:each) do 4.times do FactoryGirl.create :equipment_item, equipment_model: @eq_model end FactoryGirl.build(:checked_in_reservation, equipment_model: @eq_model).save(validate: false) @today_res = FactoryGirl.create :valid_reservation, equipment_model: @eq_model, start_date: Time.zone.today @pending_res1 = FactoryGirl.create :valid_reservation, equipment_model: @eq_model, start_date: Time.zone.today + 1.day, due_date: Time.zone.today + 3.days @pending_res2 = FactoryGirl.create :valid_reservation, equipment_model: @eq_model, start_date: Time.zone.today + 1.day, due_date: Time.zone.today + 3.days @far_future_res = FactoryGirl.create :valid_reservation, equipment_model: @eq_model, start_date: Time.zone.today + 9.days, due_date: Time.zone.today + 10.days end shared_examples 'can see pending reservations' do it 'displays the correct counts and links' do num_divs = page.all(:css, 'section#pending_reservations .giant-numbers div') expect(num_divs[0].text).to eq('1') expect(num_divs[1].text).to eq('2') expect(page).to have_link @today_res.id.to_s, href: reservation_path(@today_res) expect(page).to have_link @pending_res1.id.to_s, href: reservation_path(@pending_res1) expect(page).to have_link @pending_res2.id.to_s, href: reservation_path(@pending_res2) expect(page).not_to have_link @far_future_res.id.to_s, href: reservation_path(@far_future_res) end end shared_examples 'can see sensitive data' do it do expect(page).to have_css 'section#items' expect(page).to have_css 'section#procedures' end end shared_examples 'cannot see sensitive data' do it do expect(page).not_to have_css 'section#items' expect(page).not_to have_css 'section#procedures' end end shared_examples 'cannot see pending reservations' do it 'does not display the section' do expect(page).not_to have_css 'section#pending_reservations' end end context 'as superuser' do before do sign_in_as_user @superuser visit equipment_model_path(@eq_model) end after { sign_out } it_behaves_like 'can see pending reservations' it_behaves_like 'can see sensitive data' end context 'as admin' do before do sign_in_as_user @admin visit equipment_model_path(@eq_model) end after { sign_out } it_behaves_like 'can see pending reservations' it_behaves_like 'can see sensitive data' end context 'as checkout person' do before do sign_in_as_user @checkout_person visit equipment_model_path(@eq_model) end after { sign_out } it_behaves_like 'cannot see pending reservations' it_behaves_like 'cannot see sensitive data' end context 'as patron' do before do sign_in_as_user @user visit equipment_model_path(@eq_model) end after { sign_out } it_behaves_like 'cannot see pending reservations' it_behaves_like 'cannot see sensitive data' end context 'as guest' do before { visit equipment_model_path(@eq_model) } it_behaves_like 'cannot see pending reservations' it_behaves_like 'cannot see sensitive data' end end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/features/reservations_handling_spec.rb
spec/features/reservations_handling_spec.rb
# frozen_string_literal: true require 'spec_helper' describe 'Reservations handling', type: :feature do let(:eq_model) { FactoryGirl.create(:equipment_model_with_item) } before do sign_in_as_user(@admin) end after { sign_out } context 'with checkout procedure' do let!(:procedure) do FactoryGirl.create(:checkout_procedure, equipment_model_id: eq_model.id) end let!(:reservation) do FactoryGirl.create(:valid_reservation, reserver: @user, equipment_model: eq_model) end it 'works' do visit manage_reservations_for_user_path(@user) select eq_model.equipment_items.first.name.to_s, from: 'Equipment Item' check "reservations_#{reservation.id}_checkout_procedures_#{procedure.id}" click_button 'Check-Out Equipment' expect(page).to have_content 'Check-Out Receipt' end end context 'with checkin procedure' do let!(:procedure) do FactoryGirl.create(:checkin_procedure, equipment_model_id: eq_model.id) end let!(:reservation) do FactoryGirl.create(:checked_out_reservation, reserver: @user, equipment_model: eq_model) end it 'works' do visit manage_reservations_for_user_path(@user) check "reservations_#{reservation.id}_checkin_" check "reservations_#{reservation.id}_checkin_procedures_#{procedure.id}" click_button 'Check-In Equipment' expect(page).to have_content 'Check-In Receipt' end end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/features/reservations_archive_spec.rb
spec/features/reservations_archive_spec.rb
# frozen_string_literal: true require 'spec_helper' describe 'Reservations archiving', type: :feature do before(:each) do @res = FactoryGirl.create(:valid_reservation) end shared_examples_for 'cannot see archive button' do it do visit reservation_path(@res) expect(page).not_to have_link('Archive Reservation') end end shared_examples_for 'can archive reservation' do before { visit reservation_path(@res) } it 'can see button' do expect(page).to have_link('Archive Reservation') end it '', js: true do accept_prompt(with: 'reason') { click_link 'Archive Reservation' } expect(page).to have_content 'Reservation successfully archived.' end end context 'as patron' do before { sign_in_as_user @user } after { sign_out } it_behaves_like 'cannot see archive button' end context 'as checkout person' do before { sign_in_as_user @checkout_person } after { sign_out } it_behaves_like 'cannot see archive button' end context 'as admin' do before { sign_in_as_user @admin } after { sign_out } it_behaves_like 'can archive reservation' context 'with equipment item' do before do @ei = FactoryGirl.create(:equipment_item, equipment_model: @res.equipment_model) procedures = instance_spy(ActionController::Parameters, to_h: {}) @res.checkout(@ei.id, @admin, procedures, '').save end it_behaves_like 'can archive reservation' context 'with auto-deactivate enabled' do before do allow(@app_config).to receive(:autodeactivate_on_archive) .and_return(true) end it 'autodeactivates the equipment item', js: true do visit reservation_path(@res) accept_prompt(with: 'reason') { click_link 'Archive Reservation' } expect(page).to have_content 'has been automatically deactivated' visit equipment_item_path(@ei) expect(page).to have_content('reason') expect(page).to have_content('Status: Deactivated (reason)') end end context 'without auto-deactivate enabled', js: true do before do allow(@app_config).to receive(:autodeactivate_on_archive) .and_return(false) end it 'does not autodeactivate the equipment item' do visit reservation_path(@res) accept_prompt(with: 'reason') { click_link 'Archive Reservation' } expect(page).not_to have_content 'has been automatically deactivated' visit equipment_item_path(@ei) expect(page).to have_content('Status: available') end end context 'if checked in' do before do procedures = instance_spy(ActionController::Parameters, to_h: {}) @res.checkin(@admin, procedures, '').save end it_behaves_like 'cannot see archive button' end end end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/features/equipment_model_calendar_spec.rb
spec/features/equipment_model_calendar_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.feature 'Equipment model calendar view' do context 'as admin or superuser' do before(:each) { sign_in_as_user(@admin) } after(:each) { sign_out } it 'has useful links' do visit calendar_equipment_model_path(@eq_model) expect(page).to \ have_css "input[type=submit][value='Export Calendar']" expect(page).to have_link "Back to #{@eq_model.name}", href: equipment_model_path(@eq_model) end it 'shows all reservations in the current month', :js do create_res_in_current_month(2) visit calendar_equipment_model_path(@eq_model) expect(page).to have_css '[data-role=cal-item]', count: 2 end it 'does not show reservations next month', :js do create_res_in_current_month FactoryGirl.create(:valid_reservation, start_date: Time.zone.today + 1.month, due_date: Time.zone.today + 1.month + 1.day) visit calendar_equipment_model_path(@eq_model) expect(page).to have_css '[data-role=cal-item]', count: 1 end it 'links to the reservation', :js do res = create_res_in_current_month visit calendar_equipment_model_path(@eq_model) # this is super hacky, but the url host was super weird (127.0.0.1:37353) expect(page.find('[data-role=cal-item]')[:href]).to \ include reservation_path(res) + '.html' end end context 'as non-admin' do shared_examples 'fails' do it 'redirects to catalog' do visit calendar_equipment_model_path(@eq_model) expect(page).to have_css 'h1', text: 'Catalog' end end context 'as checkout person' do before(:each) { sign_in_as_user(@checkout_person) } after(:each) { sign_out } it_behaves_like 'fails' end context 'as patron' do before(:each) { sign_in_as_user(@user) } after(:each) { sign_out } it_behaves_like 'fails' end context 'as banned user' do before(:each) { sign_in_as_user(@banned) } after(:each) { sign_out } it_behaves_like 'fails' end end def create_res_in_current_month(count = 1) raise ArgumentError if count > 28 day0 = Time.zone.today.beginning_of_month # to ensure it's in this month (1..count).each do |i| # make sure it's a 1-day reservation so there's only a single cell # (avoid weekend overlaps) res = build :reservation, equipment_model: @eq_model, start_date: day0 + (i - 1).days, due_date: day0 + (i - 1).days, status: Reservation.statuses[:reserved] res.save(validate: false) return res if i == count # return last reservation if you want it end end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/features/blackout_spec.rb
spec/features/blackout_spec.rb
# frozen_string_literal: true require 'spec_helper' describe 'Blackout creation' do before do sign_in_as_user @admin end describe 'regular blackout' do context 'with overlapping but unaffected reservations' do before do # This reservation will start before the blackout we try to create # and end afterwards # It should not prevent the blackout from being created. FactoryGirl.create(:equipment_item, equipment_model: @eq_model) FactoryGirl.create(:reservation, equipment_model: @eq_model, due_date: Time.zone.today + 1.month) end it 'works' do visit new_blackout_path fill_in_blackout_data(start_date: Time.zone.tomorrow, end_date: Time.zone.tomorrow + 1.day) expect(page) .to have_css('.alert-success', text: /successfully created./) end end context 'with affected reservation' do before do # This reservation's due date will fall within the blackout we try to # create so we want it to fail. FactoryGirl.create(:equipment_item, equipment_model: @eq_model) FactoryGirl.create(:reservation, equipment_model: @eq_model, due_date: Time.zone.today + 2.days) end it 'fails' do visit new_blackout_path fill_in_blackout_data(start_date: Time.zone.tomorrow, end_date: Time.zone.tomorrow + 3.days) expect(page).to have_css('.alert-danger', text: /try again/) end end end describe 'recurring blackout' do context 'with affected reservations' do it 'fails' do FactoryGirl.create(:checked_out_reservation, start_date: Time.zone.tomorrow) visit new_recurring_blackout_path check_days fill_in_blackout_data(start_date: Time.zone.tomorrow, end_date: Time.zone.tomorrow + 100.days) expect(page).to have_css('.alert-danger', text: /try again/) end end context 'with unaffected reservations' do it 'succeeds' do FactoryGirl.create(:overdue_returned_reservation, start_date: Time.zone.today - 10.days, due_date: Time.zone.today - 1.day) visit new_recurring_blackout_path check_days fill_in_blackout_data(start_date: Time.zone.tomorrow + 1.day, end_date: Time.zone.tomorrow + 100.days) expect(page) .to have_css('.alert-success', text: /successfully created./) end end def check_days check 'Sun' check 'Mon' check 'Tues' check 'Wed' check 'Thurs' check 'Fri' check 'Sat' end end def fill_in_blackout_data(start_date:, end_date:) select 'Blackout', from: 'Blackout Type' fill_in_date(field: 'start', date: start_date) fill_in_date(field: 'end', date: end_date) fill_in 'Notice', with: 'Foo' click_on 'Create Blackout' end def fill_in_date(field:, date:) fill_in "blackout_#{field}_date", with: date find(:xpath, "//input[@id='date_#{field}_alt']", visible: :all) .set(date) end end describe 'Editing blackouts as admin' do let!(:blackout) do create(:blackout, created_by: @admin.id, start_date: Time.zone.today + 1, end_date: Time.zone.today + 2) end before { sign_in_as_user @admin } it 'succeeds' do visit root_path click_on 'Blackout Dates' click_on 'Edit' fill_in 'Notice', with: 'New notice' click_on 'Update Blackout' expect(page).to have_css('.alert-success', text: /successfully/) end context 'with overlapping but unaffected reservations' do before do # This reservation will start before the blackout we try to create # and end afterwards # It should not prevent the blackout from being created. FactoryGirl.create(:equipment_item, equipment_model: @eq_model) FactoryGirl.create(:reservation, equipment_model: @eq_model, due_date: Time.zone.today + 1.month) end it 'works' do visit edit_blackout_path(blackout) fill_in 'Notice', with: 'New notice' click_on 'Update Blackout' expect(page).to have_css('.alert-success', text: /successfully/) end end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/features/catalog_requirements_spec.rb
spec/features/catalog_requirements_spec.rb
# frozen_string_literal: true require 'spec_helper' describe 'Catalog view', type: :feature do context 'with requirement' do it 'renders equipment with a requirement' do @eq_model.requirements << FactoryGirl.create(:requirement) sign_in_as_user @user visit root_path expect(page).to have_css('.equipment_title_link', text: @eq_model.name) end end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/features/auth_spec.rb
spec/features/auth_spec.rb
# frozen_string_literal: true require 'spec_helper' describe 'Authentication' do subject { page } shared_examples_for 'valid registration' do it { is_expected.to have_content 'Successfully created user.' } it { is_expected.to have_content 'John Smith' } it { is_expected.to have_link 'Log Out' } end shared_examples_for 'registration error' do it { is_expected.to have_content('New User') } it { is_expected.to have_content('Please review the problems below:') } end shared_examples_for 'login error' do it { is_expected.to have_content('Sign In') } it { is_expected.to have_content('Invalid email') } it { is_expected.to have_content('or password.') } end describe 'using CAS' do # set the environment variable around(:example) do |example| env_wrapper( 'CAS_AUTH' => '1', 'USE_LDAP' => nil, 'USE_PEOPLE_API' => nil ) { example.run } end # Not sure how to check new sign_in since we're not actually using the # Devise log in function so we don't go through the post-login method. # That said, we can stub session[:new_username] to test the functionality # of the UsersController#new method context 'where user does not exist' do before do @new_user = FactoryGirl.build(:user) inject_session new_username: @new_user.username visit 'users/new' end it 'should display the form properly' do expect(page).to have_field('user_username', with: @new_user.username) expect(page).not_to have_field('user_password') end end context 'where user does exist' do # not sure how to deal with testing logging in since it's using CAS pending 'should work properly' end end describe 'using password' do # set the environment variable around(:example) do |example| env_wrapper('CAS_AUTH' => nil) { example.run } end context 'testing login and logout helpers' do before { sign_in_as_user(@checkout_person) } it 'signs in the right user' do visit root_path expect(page).to have_content(@checkout_person.name) expect(page).not_to have_link 'Sign In', href: new_user_session_path end it 'can also sign out' do sign_out visit root_path expect(page).to have_link 'Sign In', href: new_user_session_path expect(page).not_to have_content(@checkout_person.name) end end context 'with new user' do context 'can register' do before do visit '/' click_link 'Sign In', match: :first click_link 'Register' end it 'displays registration form' do expect(page).to have_field('user_password') expect(page).not_to have_field('user_username') end context 'with valid registration' do before do fill_in_registration click_button 'Create User' end it_behaves_like 'valid registration' end context 'with invalid registration' do before do fill_in_registration end context 'with mismatched passwords' do before do fill_in 'user_password_confirmation', with: 'password' click_button 'Create User' end it_behaves_like 'registration error' end context 'with missing password' do before do fill_in 'user_password', with: '' click_button 'Create User' end it_behaves_like 'registration error' end context 'with short password' do before do fill_in 'user_password', with: '1234' fill_in 'user_password_confirmation', with: '1234' click_button 'Create User' end it_behaves_like 'registration error' end context 'with missing email' do before do fill_in 'user_email', with: '' click_button 'Create User' end it_behaves_like 'registration error' end context 'with missing first name' do before do fill_in 'user_first_name', with: '' click_button 'Create User' end it_behaves_like 'registration error' end context 'with missing last name' do before do fill_in 'user_last_name', with: '' click_button 'Create User' end it_behaves_like 'registration error' end context 'with missing affiliation' do before do fill_in 'user_affiliation', with: '' click_button 'Create User' end it_behaves_like 'registration error' end context 'with existing user' do before do @user = FactoryGirl.create(:user) fill_in 'user_email', with: @user.email click_button 'Create User' end it_behaves_like 'registration error' end end end end context 'login with existing user' do before(:each) do visit '/' click_link 'Sign In', match: :first fill_in_login end it 'can log in with valid information' do click_button 'Sign in' expect(page).to have_content 'Catalog' expect(page).to have_content 'Signed in successfully.' expect(page).to have_link 'Log Out' end context 'with invalid password' do before do fill_in 'Password', with: 'wrongpassword' click_button 'Sign in' end it_behaves_like 'login error' end context 'with missing password' do before do fill_in 'Password', with: '' click_button 'Sign in' end it_behaves_like 'login error' end context 'with invalid email' do before do fill_in 'Email', with: 'wrongemail@example.com' click_button 'Sign in' end it_behaves_like 'login error' end context 'with missing email' do before do fill_in 'Email', with: '' click_button 'Sign in' end it_behaves_like 'login error' end end context 'resetting the password' do before(:each) do visit '/' click_link 'Sign In', match: :first click_link 'Forgot your password?' end it 'responds with and error for non-existant login' do fill_in 'Email', with: 'badusername@email.com' click_button 'Send me reset password instructions' expect(page).to have_content 'Forgot your password?' expect(page).to have_content 'not found' end xit 'responds correctly with valid login' do fill_in 'Email', with: @user.email click_button 'Send me reset password instructions' expect(page).to have_content 'Sign In' expect(page).to have_content 'You will receive an email with '\ 'instructions on how to reset your password in a few minutes.' end end end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/features/users_spec.rb
spec/features/users_spec.rb
# frozen_string_literal: true require 'spec_helper' describe 'Users', type: :feature do context 'can be banned' do shared_examples 'can ban other users' do it do visit user_path(@user) expect(page).to have_link 'Ban', href: ban_user_path(@user) click_link 'Ban' expect { @user.reload }.to change { @user.role }.to('banned') end end shared_examples 'cannot ban self' do it do me = current_user visit user_path(me) expect(page).not_to have_link 'Ban', href: ban_user_path(@user) end end shared_examples 'cannot ban other users' do it do visit user_path(@user) expect(page).not_to have_link 'Ban', href: ban_user_path(@user) end end context 'as superuser' do before { sign_in_as_user(@superuser) } after { sign_out } it_behaves_like 'can ban other users' it_behaves_like 'cannot ban self' end context 'as admin' do before { sign_in_as_user(@admin) } after { sign_out } it_behaves_like 'can ban other users' it_behaves_like 'cannot ban self' end context 'as checkout person' do before { sign_in_as_user(@checkout_person) } after { sign_out } it 'cannot ban other users' do visit user_path(@user) expect(page).not_to have_link 'Ban', href: ban_user_path(@user) end end end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/features/profile_spec.rb
spec/features/profile_spec.rb
# frozen_string_literal: true require 'spec_helper' describe 'User profile' do subject { page } context 'with password authentication' do around(:example) do |example| env_wrapper('CAS_AUTH' => nil) { example.run } end context 'as normal user' do before { login_as(@user, scope: :user) } context 'visiting own profile edit page' do before do visit '/users/' + @user.id.to_s click_link 'Edit Information' end it 'shows the correct fields' do expect(page).to have_field('Password') expect(page).to have_field('Password confirmation') expect(page).to have_field('Current password') expect(page).not_to have_field('Username') end context 'updating profile' do before { fill_in 'First name', with: 'Senor' } it 'updates with valid password' do fill_in 'Current password', with: 'passw0rd' click_button 'Update User' expect(page).to have_content('Senor') expect(page.find('.alert')).to\ have_content('Successfully updated user.') end it 'does not update with invalid password' do fill_in 'Current password', with: 'wrongpassword' click_button 'Update User' expect(page).to have_content('Edit Profile') expect(page).to have_content('is invalid') end it 'does not update with blank password' do click_button 'Update User' expect(page).to have_content('Edit Profile') expect(page).to have_content('can\'t be blank') end context 'changing password' do before do fill_in 'Password', with: 'newpassword' fill_in 'Current password', with: 'passw0rd' end it 'updates with valid confirmation' do fill_in 'Password confirmation', with: 'newpassword' click_button 'Update User' expect(page).to have_content('Senor') expect(page.find('.alert')).to\ have_content('Successfully updated user.') end it 'does not update with invalid confirmation' do fill_in 'Password confirmation', with: 'wrongpassword' click_button 'Update User' expect(page).to have_content('Edit Profile') expect(page).to have_content('doesn\'t match Password') end end end end context 'trying to edit a different user' do before do visit '/users/' + @admin.id.to_s end it 'redirects to home page' do expect(page).to have_content('Catalog') expect(page.find('.alert')).to\ have_content('Sorry, that action or page is restricted.') end end end context 'as admin user' do before { login_as(@admin, scope: :user) } context 'visiting own profile edit page' do before do visit '/users/' + @admin.id.to_s click_link 'Edit Information' end it 'shows the correct fields' do expect(page).to have_field('Password') expect(page).to have_field('Password confirmation') expect(page).to have_field('Current password') expect(page).not_to have_field('Username') end context 'updating profile' do before { fill_in 'First name', with: 'Senor' } it 'updates with valid password' do fill_in 'Current password', with: 'passw0rd' click_button 'Update User' expect(page).to have_content('Senor') expect(page.find('.alert')).to\ have_content('Successfully updated user.') end it 'does not update with invalid password' do fill_in 'Current password', with: 'wrongpassword' click_button 'Update User' expect(page).to have_content('Edit Profile') expect(page).to have_content('is invalid') end it 'does not update with blank password' do click_button 'Update User' expect(page).to have_content('Edit Profile') expect(page).to have_content('can\'t be blank') end context 'changing password' do before do fill_in 'Password', with: 'newpassword' fill_in 'Current password', with: 'passw0rd' end it 'updates with valid confirmation' do fill_in 'Password confirmation', with: 'newpassword' click_button 'Update User' expect(page).to have_content('Senor') expect(page.find('.alert')).to\ have_content('Successfully updated user.') end it 'does not update with invalid confirmation' do fill_in 'Password confirmation', with: 'wrongpassword' click_button 'Update User' expect(page).to have_content('Edit Profile') expect(page).to have_content('doesn\'t match Password') end end end end context 'trying to edit a different user' do before do visit '/users/' + @user.id.to_s click_link 'Edit Information' end it 'shows the correct fields' do expect(page).not_to have_field('Password') expect(page).not_to have_field('Password confirmation') expect(page).not_to have_field('Current password') expect(page).not_to have_field('Username') end it 'can update profile' do fill_in 'First name', with: 'Senor' click_button 'Update User' expect(page).to have_content('Senor') expect(page.find('.alert')).to\ have_content('Successfully updated user.') end end end end context 'with CAS authentication' do around(:example) do |example| env_wrapper('CAS_AUTH' => '1') { example.run } end context 'as normal user' do before { login_as(@user, scope: :user) } context 'visiting own profile edit page' do before do visit '/users/' + @user.id.to_s click_link 'Edit Information' end it 'shows the correct fields' do expect(page).not_to have_field('Password') expect(page).not_to have_field('Password confirmation') expect(page).not_to have_field('Current password') expect(page).to have_field('Username') end it 'can update profile' do fill_in 'First name', with: 'Senor' click_button 'Update User' expect(page).to have_content('Senor') expect(page.find('.alert')).to\ have_content('Successfully updated user.') end end context 'trying to edit a different user' do before do visit '/users/' + @admin.id.to_s end it 'redirects to home page' do expect(page).to have_content('Catalog') expect(page.find('.alert')).to\ have_content('Sorry, that action or page is restricted.') end end end context 'as admin user' do before { login_as(@admin, scope: :user) } context 'visiting own profile edit page' do before do visit '/users/' + @admin.id.to_s click_link 'Edit Information' end it 'shows the correct fields' do expect(page).not_to have_field('Password') expect(page).not_to have_field('Password confirmation') expect(page).not_to have_field('Current password') expect(page).to have_field('Username') end it 'can update profile' do fill_in 'First name', with: 'Senor' click_button 'Update User' expect(page).to have_content('Senor') expect(page.find('.alert')).to\ have_content('Successfully updated user.') end end context 'trying to edit a different user' do before do visit '/users/' + @user.id.to_s click_link 'Edit Information' end it 'shows the correct fields' do expect(page).not_to have_field('Password') expect(page).not_to have_field('Password confirmation') expect(page).not_to have_field('Current password') expect(page).to have_field('Username') end it 'can update profile' do fill_in 'First name', with: 'Senor' click_button 'Update User' expect(page).to have_content('Senor') expect(page.find('.alert')).to\ have_content('Successfully updated user.') end end end end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/features/rails_admin_spec.rb
spec/features/rails_admin_spec.rb
# frozen_string_literal: true require 'spec_helper' describe 'Active Admin', type: :feature do VALID_MODELS = [:announcement, :app_config, :blackout, :category, :checkin_procedure, :checkout_procedure, :equipment_item, :equipment_model, :requirement, :reservation, :user].freeze context 'as superuser' do before { sign_in_as_user(@superuser) } after { sign_out } shared_examples 'can access route' do |model| let(:path) do admin_routes.index_url(model_name: model, host: Capybara.default_host) end it do visit path expect(page.current_url).to eq(path) end end it 'can access the dashboard' do visit admin_routes.dashboard_path expect(page).to have_content 'Site Administration' expect(page.current_url).to \ eq(admin_routes.dashboard_url(host: Capybara.default_host)) end VALID_MODELS.each do |mod| it_behaves_like 'can access route', mod end it 'can delete equipment items' do visit admin_routes.show_url(model_name: :equipment_item, id: @eq_item.id, host: Capybara.default_host) click_link 'Delete' click_button "Yes, I'm sure" expect(EquipmentItem.find_by(id: @eq_item.id)).to be_nil end end context 'as other roles' do shared_examples 'cannot access route' do |model| if model let(:path) { admin_routes.index_path(model_name: model) } else let(:path) { admin_routes.dashboard_path } end it do visit path expect(page.current_url).to eq(root_url(host: Capybara.default_host)) end end context 'as patron' do before { sign_in_as_user(@user) } after { sign_out } it_behaves_like 'cannot access route' VALID_MODELS.each do |mod| it_behaves_like 'cannot access route', mod end end context 'as checkout person' do before { sign_in_as_user(@checkout_person) } after { sign_out } it_behaves_like 'cannot access route' VALID_MODELS.each do |mod| it_behaves_like 'cannot access route', mod end end context 'as admin' do before { sign_in_as_user(@admin) } after { sign_out } it_behaves_like 'cannot access route' VALID_MODELS.each do |mod| it_behaves_like 'cannot access route', mod end end end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/features/announcements_spec.rb
spec/features/announcements_spec.rb
# frozen_string_literal: true require 'spec_helper' describe 'Announcements' do before :each do Announcement.create! message: 'Hello World', starts_at: Time.zone.today - 1.day, ends_at: Time.zone.today + 1.day Announcement.create! message: 'Upcoming', starts_at: Time.zone.today + 1.day, ends_at: Time.zone.today + 2.days end it 'displays active announcements' do visit '/' expect(page).to have_content('Hello World') expect(page).not_to have_content('Upcoming') end # 2014-10-24 # Testing the close button is problematic because I think we're using a JS # response and for some reason selenium isn't liking it. I also ran into # issues with missing routes for 'favicon.ico' unless I make the before # block "before :all". # context "after pressing the close button", :js => true do # before do # visit '/' # click_button('close_announcement') # visit current_path # end # it { expect(page).not_to have_content("Hello World") } # end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/features/reservations_spec.rb
spec/features/reservations_spec.rb
# frozen_string_literal: true require 'spec_helper' describe 'Reservations', type: :feature do context 'can be created' do before(:each) { empty_cart } shared_examples 'can create valid reservation' do |reserver| let(:reserver) { reserver } str = reserver ? 'for other user successfully' : 'successfully' it str do visit root_path change_reserver(reserver) if reserver add_item_to_cart(@eq_model) update_cart_start_date(Time.zone.today) due_date = Time.zone.today + 1.day update_cart_due_date(due_date) # request catalog since our update cart methods only return the cart # partial from the JS update (so the 'Reserve' link wouldn't be there) visit root_path click_link 'Reserve', href: new_reservation_path # set reserver to current user if unset, check confirmation page reserver = reserver ? reserver : @current_user expect(page).to have_content reserver.name expect(page).to have_content Time.zone.today.to_s(:long) expect(page).to have_content due_date.to_s(:long) expect(page).to have_content @eq_model.name expect(page).to have_content 'Confirm Reservation' click_button 'Finalize Reservation' # check that reservation was created with correct dates query = Reservation.for_eq_model(@eq_model.id).for_reserver(reserver.id) expect(query.count).to eq(1) expect(query.first.start_date).to eq(Time.zone.today) expect(query.first.due_date).to eq(due_date) expect(query.first.status).to eq('reserved') end end shared_examples 'can create reservation request' do |reserver| let(:reserver) { reserver } str = reserver ? 'for other user successfully' : 'successfully' it str do visit root_path change_reserver(reserver) if reserver add_item_to_cart(@eq_model) update_cart_start_date(Time.zone.today) # violate length validation bad_due_date = Time.zone.today + (@eq_model.maximum_checkout_length + 1).days update_cart_due_date(bad_due_date) # request catalog since our update cart methods only return the cart # partial from the JS update (so the 'Reserve' link wouldn't be there) visit root_path click_link 'Reserve', href: new_reservation_path # set reserver to current user if unset, check confirmation page reserver = reserver ? reserver : @current_user expect(page).to have_content reserver.name expect(page).to have_content Time.zone.today.to_s(:long) expect(page).to have_content bad_due_date.to_s(:long) expect(page).to have_content @eq_model.name expect(page).to have_content 'Confirm Reservation Request' find(:xpath, "//textarea[@id='reservation_notes']").set 'Because' click_button 'Submit Request' # check that reservation request was created with correct dates query = Reservation.for_eq_model(@eq_model.id).for_reserver(reserver.id) expect(query.count).to eq(1) expect(query.first.start_date).to eq(Time.zone.today) expect(query.first.due_date).to eq(bad_due_date) expect(query.first.status).to eq('requested') end end shared_examples 'can create failing reservation' do |reserver| let(:reserver) { reserver } str = reserver ? 'for other user successfully' : 'successfully' it str do visit root_path change_reserver(reserver) if reserver add_item_to_cart(@eq_model) update_cart_start_date(Time.zone.today) # violate length validation bad_due_date = Time.zone.today + (@eq_model.maximum_checkout_length + 1).days update_cart_due_date(bad_due_date) # request catalog since our update cart methods only return the cart # partial from the JS update (so the 'Reserve' link wouldn't be there) visit root_path click_link 'Reserve', href: new_reservation_path # set reserver to current user if unset, check confirmation page reserver = reserver ? reserver : @current_user expect(page).to have_content reserver.name expect(page).to have_content Time.zone.today.to_s(:long) expect(page).to have_content bad_due_date.to_s(:long) expect(page).to have_content @eq_model.name expect(page).to have_content 'Confirm Reservation' expect(page).to have_content 'Please be aware of the following errors:' find(:xpath, "//textarea[@id='reservation_notes']").set 'Because' click_button 'Finalize Reservation' # check that reservation was created with correct dates query = Reservation.for_eq_model(@eq_model.id).for_reserver(reserver.id) expect(query.count).to eq(1) expect(query.first.start_date).to eq(Time.zone.today) expect(query.first.due_date).to eq(bad_due_date) expect(query.first.status).to eq('reserved') end end context 'by patrons' do before { sign_in_as_user(@user) } after { sign_out } it_behaves_like 'can create valid reservation' it_behaves_like 'can create reservation request' end context 'by checkout persons' do before { sign_in_as_user(@checkout_person) } after { sign_out } context 'without override permissions' do before do allow(@app_config).to receive(:override_on_create).and_return(false) end it_behaves_like 'can create valid reservation', @user it_behaves_like 'can create reservation request', @user end context 'with override permissions' do before do allow(@app_config).to receive(:override_on_create).and_return(true) end it_behaves_like 'can create failing reservation', @user end end context 'by admins' do before { sign_in_as_user(@admin) } after { sign_out } context 'with override disabled' do before do allow(@app_config).to receive(:override_on_create).and_return(false) end it_behaves_like 'can create valid reservation', @user it_behaves_like 'can create failing reservation', @user end context 'with override enabled' do before do allow(@app_config).to receive(:override_on_create).and_return(true) end it_behaves_like 'can create failing reservation', @user end end context 'by superusers' do before { sign_in_as_user(@superuser) } after { sign_out } context 'with override disabled' do before do allow(@app_config).to receive(:override_on_create).and_return(false) end it_behaves_like 'can create valid reservation', @user it_behaves_like 'can create failing reservation', @user end context 'with override enabled' do before do allow(@app_config).to receive(:override_on_create).and_return(true) end it_behaves_like 'can create failing reservation', @user end end end context 'banned equipment processing' do after(:each) do @user.update(role: 'normal') end shared_examples 'can handle banned user reservation transactions' do it 'checks in successfully' do # check in @checked_out_res = FactoryGirl.create :checked_out_reservation, reserver: @user, equipment_model: @eq_model @user.update(role: 'banned') visit manage_reservations_for_user_path(@user) check @checked_out_res.equipment_item.name.to_s click_button 'Check-In Equipment' expect(page).to have_content 'Check-In Receipt' expect(page).to have_content current_user.name @checked_out_res.reload expect(@checked_out_res.checkin_handler).to eq(current_user) expect(@checked_out_res.checked_in).not_to be_nil end it 'cannot checkout successfully' do @res = FactoryGirl.create :valid_reservation, reserver: @user, equipment_model: @eq_model @user.update(role: 'banned') # check out visit manage_reservations_for_user_path(@user) select @eq_model.equipment_items.first.name.to_s, from: 'Equipment Item' click_button 'Check-Out Equipment' expect(page).to have_content 'Banned users cannot check out equipment' end end context 'as checkout person' do before { sign_in_as_user(@checkout_person) } after { sign_out } it_behaves_like 'can handle banned user reservation transactions' end context 'as admin' do before { sign_in_as_user(@admin) } after { sign_out } it_behaves_like 'can handle banned user reservation transactions' end context 'as superuser' do before { sign_in_as_user(@superuser) } after { sign_out } it_behaves_like 'can handle banned user reservation transactions' end end context 'equipment processing' do before(:each) do @res = FactoryGirl.create :valid_reservation, reserver: @user, equipment_model: @eq_model visit manage_reservations_for_user_path(@user) end shared_examples 'can handle reservation transactions' do it 'checks out and checks in successfully' do # check out visit manage_reservations_for_user_path(@user) select @eq_model.equipment_items.first.name.to_s, from: 'Equipment Item' click_button 'Check-Out Equipment' expect(page).to have_content 'Check-Out Receipt' expect(page).to have_content current_user.name @res.reload expect(@res.equipment_item_id).to eq(@eq_model.equipment_items.first.id) expect(@res.checkout_handler).to eq(current_user) expect(@res.checked_out).not_to be_nil # check equipment item notes if admin or superuser (checkout persons # can't see them) if current_user.view_mode == 'admin' || current_user.view_mode == 'superuser' visit equipment_item_path(@res.equipment_item) expect(page).to have_link('Checked out', href: resource_url(@res)) end # check in visit manage_reservations_for_user_path(@user) check @res.equipment_item.name.to_s click_button 'Check-In Equipment' expect(page).to have_content 'Check-In Receipt' expect(page).to have_content current_user.name @res.reload expect(@res.checkin_handler).to eq(current_user) expect(@res.checked_in).not_to be_nil if current_user.view_mode == 'admin' || current_user.view_mode == 'superuser' visit equipment_item_path(@res.equipment_item) expect(page).to have_link('Checked in', href: resource_url(@res)) end end it 'does not update equipment items for missing ToS checkbox' do @user.update(terms_of_service_accepted: false) visit manage_reservations_for_user_path(@user) select @eq_model.equipment_items.first.name.to_s, from: 'Equipment Item' click_button 'Check-Out Equipment' expect(page).to have_content 'You must confirm that the user accepts '\ 'the Terms of Service.' visit equipment_item_path(@res.equipment_model.equipment_items.first) expect(page).not_to have_link('Checked out', href: resource_url(@res)) end it 'does not update equipment items for duplicate items' do FactoryGirl.create :equipment_item, equipment_model: @eq_model, name: 'name2' @res2 = FactoryGirl.create :valid_reservation, reserver: @user, equipment_model: @eq_model visit manage_reservations_for_user_path(@user) select @eq_model.equipment_items.first.name.to_s, from: "reservations_#{@res.id}_equipment_item_id" select @eq_model.equipment_items.first.name.to_s, from: "reservations_#{@res2.id}_equipment_item_id" click_button 'Check-Out Equipment' expect(page).to have_content 'The same equipment item cannot be '\ 'simultaneously checked out in multiple reservations.' visit equipment_item_path(@res.equipment_model.equipment_items.first) expect(page).not_to have_link('Checked out', href: resource_url(@res)) expect(page).not_to have_link('Checked out', href: resource_url(@res2)) end end context 'as guest' do it 'should redirect to the catalog page' do visit manage_reservations_for_user_path(@user) expect(page).to have_content 'Sign In' expect(page.current_url).to eq(new_user_session_url) end end context 'as patron' do before { sign_in_as_user(@user) } after { sign_out } it 'should redirect to the catalog page' do visit manage_reservations_for_user_path(@user) expect(page).to have_content 'Catalog' expect(page.current_url).to eq(root_url) end end context 'as checkout person' do before { sign_in_as_user(@checkout_person) } after { sign_out } it_behaves_like 'can handle reservation transactions' end context 'as admin' do before { sign_in_as_user(@admin) } after { sign_out } it_behaves_like 'can handle reservation transactions' end context 'as superuser' do before { sign_in_as_user(@superuser) } after { sign_out } it_behaves_like 'can handle reservation transactions' end context 'ToS checkbox' do before(:each) do @user.update(terms_of_service_accepted: false) end shared_examples 'can utilize the ToS checkbox' do before(:each) { visit manage_reservations_for_user_path(@user) } it 'fails when the box isn\'t checked off' do # skip the checkbox select @eq_model.equipment_items.first.name.to_s, from: 'Equipment Item' click_button 'Check-Out Equipment' expect(page).to have_content 'You must confirm that the user '\ 'accepts the Terms of Service.' expect(page.current_url).to \ eq(manage_reservations_for_user_url(@user)) end it 'succeeds when the box is checked off' do check 'terms_of_service_accepted' select @eq_model.equipment_items.first.name.to_s, from: 'Equipment Item' click_button 'Check-Out Equipment' expect(page).to have_content 'Check-Out Receipt' expect(page).to have_content current_user.name @res.reload expect(@res.equipment_item_id).to \ eq(@eq_model.equipment_items.first.id) expect(@res.checkout_handler).to eq(current_user) expect(@res.checked_out).not_to be_nil end end context 'as checkout person' do before { sign_in_as_user(@checkout_person) } after { sign_out } it_behaves_like 'can utilize the ToS checkbox' end context 'as admin' do before { sign_in_as_user(@admin) } after { sign_out } it_behaves_like 'can utilize the ToS checkbox' end context 'as superuser' do before { sign_in_as_user(@superuser) } after { sign_out } it_behaves_like 'can utilize the ToS checkbox' end end end context 'renewing reservations' do before(:each) do @res = FactoryGirl.create :checked_out_reservation, reserver: @user, equipment_model: @eq_model end shared_examples 'can see renew button' do before { visit reservation_path(@res) } it { expect(page).to have_content 'You are currently eligible to renew' } end shared_examples 'cannot see renew button' do before { visit reservation_path(@res) } it do expect(page).to have_content 'This item is not currently eligible '\ 'for renewal.' end end shared_examples 'can renew reservation when enabled and available' do it do allow(@app_config).to receive(:enable_renewals).and_return(true) visit reservation_path(@res) expect(page).to have_content 'You are currently eligible to renew' click_link 'Renew Now', href: renew_reservation_path(@res) expect(page).to have_content 'Your reservation has been renewed' expect { @res.reload }.to change { @res.due_date } end end shared_examples 'cannot see renew button when disabled' do it do allow(@app_config).to receive(:enable_renewals).and_return(false) visit reservation_path(@res) expect(page).not_to have_link 'Renew Now', href: renew_reservation_path(@res) end end shared_examples 'cannot renew reservation when unavailable' do it do allow(@app_config).to receive(:enable_renewals).and_return(true) FactoryGirl.create :reservation, equipment_model: @eq_model, start_date: @res.due_date + 1.day, due_date: @res.due_date + 2.days visit reservation_path(@res) expect(page).to have_content 'This item is not currently eligible '\ 'for renewal.' end end context 'as patron' do before { sign_in_as_user(@user) } after { sign_out } it_behaves_like 'can renew reservation when enabled and available' it_behaves_like 'cannot see renew button when disabled' it_behaves_like 'cannot renew reservation when unavailable' end context 'as checkout person' do before { sign_in_as_user(@checkout_person) } after { sign_out } it_behaves_like 'can renew reservation when enabled and available' it_behaves_like 'cannot see renew button when disabled' it_behaves_like 'cannot renew reservation when unavailable' end context 'as admin' do before { sign_in_as_user(@admin) } after { sign_out } it_behaves_like 'can renew reservation when enabled and available' it_behaves_like 'cannot see renew button when disabled' it_behaves_like 'cannot renew reservation when unavailable' context 'respects setting renewal_days_before_due' do before do @res.equipment_model.update(renewal_days_before_due: 5) end context 'before limit' do before { @res.update(due_date: Time.zone.today + 6.days) } it_behaves_like 'cannot see renew button' end context 'after limit' do before { @res.update(due_date: Time.zone.today + 5.days) } it_behaves_like 'can see renew button' end end context 'respects setting max_renewal_times' do before { @res.equipment_model.update(max_renewal_times: 3) } context 'at limit' do before { @res.update(times_renewed: 3) } it_behaves_like 'cannot see renew button' end context 'below limit' do before { @res.update(times_renewed: 2) } it_behaves_like 'can see renew button' end end context 'cannot renew if the reservation is overdue' do # rubocop:disable Rails/SkipsModelValidations before { @res.update_columns(overdue: true) } # rubocop:enable Rails/SkipsModelValidations it_behaves_like 'cannot see renew button' end end context 'as superuser' do before { sign_in_as_user(@superuser) } after { sign_out } it_behaves_like 'can renew reservation when enabled and available' it_behaves_like 'cannot renew reservation when unavailable' it 'can see renew button when disabled' do allow(@app_config).to receive(:enable_renewals).and_return(false) visit reservation_path(@res) expect(page).to have_link 'Renew Now', href: renew_reservation_path(@res) end end end context 'valid items on confirmation page' do before(:each) do empty_cart add_item_to_cart(@eq_model) update_cart_start_date(Time.zone.today) due_date = Time.zone.today + 1.day update_cart_due_date(due_date) end shared_examples 'can make valid change to reservation' do |reserver| before(:each) do visit new_reservation_path end let(:reserver) { reserver } str = reserver ? 'for other user successfully' : 'successfully' it str do quantity_forms = page.all('#quantity_form') avail_quantity = @eq_model.num_available(Time.zone.today, Time.zone.today + 1.day) fill_in "quantity_field_#{@eq_model.id}", # edit and submit with: avail_quantity quantity_forms[0].submit_form! # loading right page expect(page).to have_content 'Confirm Reservation' expect(page).not_to have_content 'Confirm Reservation Request' # changes applied expect(page).to have_selector("input[value='#{avail_quantity}']") end end shared_examples 'will load request page if item is invalid' do |reserver| before(:each) do allow(@app_config).to receive(:override_on_create).and_return(false) visit new_reservation_path end let(:reserver) { reserver } str = reserver ? 'for other user successfully' : 'successfully' it str do # change cart to have invalid properties, and check if it loads request quantity_forms = page.all('#quantity_form') fill_in "quantity_field_#{@eq_model.id}", with: (@eq_model.max_per_user + 1) quantity_forms[0].submit_form! # loading right page expect(page).to have_content 'Confirm Reservation Request' expect(page).to have_content AppConfig.get(:request_text) # changes applied expect(page).to \ have_selector("input[value='#{@eq_model.max_per_user + 1}']") end end shared_examples 'can remove a valid item' do |reserver| before(:each) do @eq_model2 = FactoryGirl.create(:equipment_model, category: @category) FactoryGirl.create(:equipment_item, equipment_model: @eq_model2) add_item_to_cart(@eq_model2) visit new_reservation_path end let(:reserver) { reserver } str = reserver ? 'for other user successfully' : 'successfully' it str do # removing a valid item quantity_forms = page.all('#quantity_form') fill_in "quantity_field_#{@eq_model.id}", with: 0 quantity_forms[0].submit_form! # changes applied expect(page).not_to have_content @eq_model.name end end shared_examples 'can remove all items' do |reserver| before(:each) do @eq_model2 = FactoryGirl.create(:equipment_model, category: @category) FactoryGirl.create(:equipment_item, equipment_model: @eq_model2) add_item_to_cart(@eq_model2) visit new_reservation_path end let(:reserver) { reserver } str = reserver ? 'for other user successfully' : 'successfully' it str do # removing all items quantity_forms = page.all('#quantity_form') fill_in "quantity_field_#{@eq_model.id}", with: 0 quantity_forms[0].submit_form! quantity_forms = page.all('#quantity_form') # gets an updated page fill_in "quantity_field_#{@eq_model2.id}", with: 0 quantity_forms[0].submit_form! # redirects to catalog (implies that cart is empty) expect(page).to have_content 'Catalog' expect(page).not_to have_content 'Confirm Reservation' end end shared_examples 'can make valid date change' do |reserver| before(:each) do visit new_reservation_path end let(:reserver) { reserver } str = reserver ? 'for other user successfully' : 'successfully' it str do # valid change due_date = Time.zone.today + 2.days fill_in 'cart_due_date_cart', with: due_date find(:xpath, "//input[@id='date_end_alt']", visible: :all).set due_date find('#dates_form').submit_form! # loads right page expect(page).to have_content 'Confirm Reservation' expect(page).not_to have_content 'Confirm Reservation Request' # has correct date expect(page).to have_selector("input[value='#{due_date}']", visible: :all) end end shared_examples 'will load request if invalid date change' do |reserver| before(:each) do allow(@app_config).to receive(:override_on_create).and_return(false) visit new_reservation_path end let(:reserver) { reserver } str = reserver ? 'for other user successfully' : 'successfully' it str do # change to invalid date bad_due_date = Time.zone.today + (@eq_model.maximum_checkout_length + 1).days fill_in 'cart_due_date_cart', with: bad_due_date find(:xpath, "//input[@id='date_end_alt']", visible: :all) .set bad_due_date find('#dates_form').submit_form! # loads right page expect(page).to have_content 'Confirm Reservation Request' expect(page).to have_content AppConfig.get(:request_text) # has altered date expect(page).to have_selector("input[value='#{bad_due_date}']", visible: :all) end end shared_examples 'can change back to valid dates after invalid' do |reserver| before(:each) do visit new_reservation_path end let(:reserver) { reserver } str = reserver ? 'for other user successfully' : 'successfully' it str do # change to invalid date bad_due_date = Time.zone.today + (@eq_model.maximum_checkout_length + 1).days fill_in 'cart_due_date_cart', with: bad_due_date find(:xpath, "//input[@id='date_end_alt']", visible: :all) .set bad_due_date find('#dates_form').submit_form! # changes back to valid date due_date = Time.zone.today + 1.day fill_in 'cart_due_date_cart', with: due_date find(:xpath, "//input[@id='date_end_alt']", visible: :all).set due_date find('#dates_form').submit_form! # redirect to right page expect(page).to have_content 'Confirm Reservation' expect(page).not_to have_content 'Confirm Reservation Request' # has correct dates expect(page).to have_selector("input[value='#{due_date}']", visible: :all) end end context 'as patron' do before { sign_in_as_user(@user) } after { sign_out } it_behaves_like 'can make valid change to reservation' it_behaves_like 'will load request page if item is invalid' it_behaves_like 'can remove a valid item' it_behaves_like 'can remove all items' it_behaves_like 'can make valid date change' it_behaves_like 'will load request if invalid date change' it_behaves_like 'can change back to valid dates after invalid' end context 'as checkout person' do before { sign_in_as_user(@checkout_person) } after { sign_out } it_behaves_like 'can make valid change to reservation' it_behaves_like 'will load request page if item is invalid' it_behaves_like 'can remove a valid item' it_behaves_like 'can remove all items' it_behaves_like 'can make valid date change' it_behaves_like 'will load request if invalid date change' it_behaves_like 'can change back to valid dates after invalid' end end context 'invalid items on confirm page' do before(:each) do empty_cart @eq_model2 = FactoryGirl.create(:equipment_model, category: @category) FactoryGirl.create(:equipment_item, equipment_model: @eq_model2) add_item_to_cart(@eq_model) add_item_to_cart(@eq_model2) quantity_forms = page.all('#quantity_form') fill_in "quantity_field_#{@eq_model.id}", with: (@eq_model.max_per_user + 1) quantity_forms[0].submit_form! update_cart_start_date(Time.zone.today) due_date = Time.zone.today + 1.day update_cart_due_date(due_date) visit new_reservation_path end shared_examples 'loads reservation page if item is now valid' do |reserver| let(:reserver) { reserver } str = reserver ? 'for other user successfully' : 'successfully' it str do # change cart to have invalid properties, and check if it loads request quantity_forms = page.all('#quantity_form') fill_in "quantity_field_#{@eq_model.id}", with: @eq_model.max_per_user quantity_forms[0].submit_form! expect(page).to have_content 'Confirm Reservation' end end shared_examples 'can remove an invalid item' do |reserver| let(:reserver) { reserver } str = reserver ? 'for other user successfully' : 'successfully' it str do # removing a valid item quantity_forms = page.all('#quantity_form') fill_in "quantity_field_#{@eq_model.id}", with: 0 quantity_forms[0].submit_form! expect(page).not_to have_content @eq_model.name end end context 'as patron' do before { sign_in_as_user(@user) } after { sign_out } it_behaves_like 'loads reservation page if item is now valid' it_behaves_like 'can remove an invalid item' end context 'as checkout person' do before { sign_in_as_user(@checkout_person) } after { sign_out } it_behaves_like 'loads reservation page if item is now valid' it_behaves_like 'can remove an invalid item' end end context 'accessing /reservation/new path with empty cart' do before(:each) do sign_in_as_user(@admin) empty_cart visit equipment_model_path(@eq_model) end after(:each) { sign_out } it 'handles direct url' do visit new_reservation_path expect(page.current_url).to include(root_path) expect(page).to have_content('Catalog') end it 'handles pressing reserve button' do click_link('Reserve') expect(page.current_url).to include(equipment_models_path) expect(page).to have_content('Description') end end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/features/guest_spec.rb
spec/features/guest_spec.rb
# frozen_string_literal: true require 'spec_helper' describe 'guest users', type: :feature do # Shared Examples shared_examples 'unauthorized' do context 'visiting protected route' do describe '/reservations/new' do it_behaves_like('inaccessible to guests', :new_reservation_path) end describe '/reservations' do it_behaves_like('inaccessible to guests', :reservations_path) end describe '/users' do it_behaves_like('inaccessible to guests', :users_path) end describe '/app_configs/edit' do it_behaves_like('inaccessible to guests', :edit_app_configs_path) end end end # based on http://www.tkalin.com/blog_posts/testing-authorization-using-rspec-parametrized-shared-examples/ shared_examples 'inaccessible to guests' do |url, mod| if mod let(:url_path) { send(url, mod.first.id) } else let(:url_path) { send(url) } end it 'redirects to the signin page with errors' do visit url_path expect(current_path).to eq(new_user_session_path) expect(page).to have_selector('.alert-danger') end end shared_examples 'accessible to guests' do |url, mod| if mod let(:url_path) { send(url, mod.first.id) } else let(:url_path) { send(url) } end it 'goes to the correct page with sign in link' do visit url_path expect(current_path).to eq(url_path) expect(page).to have_link('Sign In', href: new_user_session_path) end end context 'when enabled' do before(:each) do allow(@app_config).to receive(:enable_guests).and_return(true) end it 'correctly sets the setting' do expect(AppConfig.check(:enable_guests)).to be_truthy end it_behaves_like 'unauthorized' context 'visiting permitted route' do describe '/' do it_behaves_like('accessible to guests', :root_path) end describe '/catalog' do it_behaves_like('accessible to guests', :catalog_path) end describe '/equipment_models/:id' do it_behaves_like('accessible to guests', :equipment_model_path, EquipmentModel) end describe '/categories/:id/equipment_models' do it_behaves_like('accessible to guests', :category_equipment_models_path, Category) end describe '/terms_of_service' do it_behaves_like('accessible to guests', :tos_path) end end describe 'can use the catalog' do before :each do add_item_to_cart(@eq_model) visit '/' end it 'can add items to cart' do expect(page.find(:css, '#list_items_in_cart')).to \ have_link(@eq_model.name, href: equipment_model_path(@eq_model)) end it 'can remove items from cart' do quantity = 0 fill_in "quantity_field_#{EquipmentModel.first.id}", with: quantity.to_s find('#quantity_form').submit_form! visit '/' expect(page.find(:css, '#list_items_in_cart')).not_to \ have_link(@eq_model.name, href: equipment_model_path(@eq_model)) end it 'can change item quantities' do quantity = 3 fill_in "quantity_field_#{EquipmentModel.first.id}", with: quantity.to_s find('#quantity_form').submit_form! visit '/' expect(page.find("#quantity_field_#{EquipmentModel.first.id}").value) \ .to eq(quantity.to_s) end it 'can change the dates' do @new_date = Time.zone.today + 5.days update_cart_due_date(@new_date.to_s) visit '/' expect(page.find('#cart_due_date_cart').value).to \ eq(@new_date.strftime('%m/%d/%Y')) end end end context 'when disabled' do before(:each) do allow(@app_config).to receive(:enable_guests).and_return(false) end it 'correctly sets the setting' do expect(AppConfig.check(:enable_guests)).to be_falsey end it_behaves_like 'unauthorized' context 'visiting nominally permitted route' do describe '/' do it_behaves_like('inaccessible to guests', :root_path) end describe '/catalog' do it_behaves_like('inaccessible to guests', :catalog_path) end describe '/equipment_models/:id' do it_behaves_like('inaccessible to guests', :equipment_model_path, EquipmentModel) end describe '/categories/:id/equipment_models' do it_behaves_like('inaccessible to guests', :category_equipment_models_path, Category) end describe '/terms_of_service' do it_behaves_like('inaccessible to guests', :tos_path) end end end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/features/equipment_model_views_spec.rb
spec/features/equipment_model_views_spec.rb
# frozen_string_literal: true require 'spec_helper' describe 'Equipment model views' do subject { page } context 'index view' do shared_examples 'can view detailed table' do it { should have_selector 'th', text: 'Available' } end shared_examples 'can view full and detailed table' do it_behaves_like 'can view detailed table' it { expect(page).to have_link 'Edit' } end shared_examples 'displays appropriate information' do it { is_expected.to have_content('Equipment Models') } it { is_expected.to have_content(@eq_model.name) } end context 'check for super user' do before do sign_in_as_user(@superuser) visit equipment_models_path end after { sign_out } it_behaves_like 'can view full and detailed table' it_behaves_like 'displays appropriate information' end context 'check for admin' do before do sign_in_as_user(@admin) visit equipment_models_path end after { sign_out } it_behaves_like 'can view full and detailed table' it_behaves_like 'displays appropriate information' end context 'check for patron' do before do sign_in_as_user(@user) visit equipment_models_path end after { sign_out } it_behaves_like 'can view detailed table' it_behaves_like 'displays appropriate information' end context 'check for check out person' do before do sign_in_as_user(@checkout_person) visit equipment_models_path end after { sign_out } it_behaves_like 'can view detailed table' it_behaves_like 'displays appropriate information' end context 'check for guest' do before { visit equipment_models_path } it { should_not have_selector 'th', text: 'Available' } it_behaves_like 'displays appropriate information' end context 'check for banned user' do before do sign_in_as_user(@banned) visit equipment_models_path end after { sign_out } it { should_not have_selector 'th', text: 'Available' } it { is_expected.not_to have_content('Equipment Models') } end end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/queries/reservations/affected_by_recurring_blackout_query.rb
spec/queries/reservations/affected_by_recurring_blackout_query.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe Reservations::AffectedByRecurringBlackoutQuery do let!(:overdue) do create(:overdue_reservation, due_date: Time.zone.today - 1.day) end let!(:checked_out) do create(:checked_out_reservation, due_date: Time.zone.tomorrow) end let!(:no_problem) do create(:checked_out_reservation, due_date: Time.zone.today + 4.days) end let!(:archived) { create(:archived_reservation) } let!(:checked_in) { create(:checked_in_reservation) } let!(:reserved) do create(:valid_reservation, start_date: Time.zone.tomorrow, due_date: Time.zone.today + 2.days) end let!(:res_dates) do [Time.zone.tomorrow, Time.zone.tomorrow + 1.day] end it 'returns reservations which have due/start date in a blackout range' do expect(described_class.call(res_dates)) .to match_array([reserved, checked_out]) end it 'works with a custom relation passed in' do custom_relation = Reservation.where.not(id: checked_out.id) expect(described_class.new(custom_relation).call(res_dates)) .to match_array([reserved]) end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/lib/class_from_string_spec.rb
spec/lib/class_from_string_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe ClassFromString do shared_examples 'valid class' do |method, string, klass| it 'returns a model class' do expect(described_class.send(method, string)).to eq(klass) end end shared_examples 'invalid class' do |method, string| it 'returns a model class' do expect { described_class.send(method, string) }.to raise_error(KeyError) end end REPORTS = { 'equipment_model' => EquipmentModel, 'category' => Category, 'user' => User, 'equipment_item' => EquipmentItem }.freeze EQUIPMENT = { 'equipment_items' => EquipmentItem, 'equipment_models' => EquipmentModel, 'categories' => Category }.freeze describe '.reports!' do REPORTS.each { |k, v| it_behaves_like 'valid class', :reports!, k, v } it_behaves_like 'invalid class', :reports!, 'logger' end describe '.equipment!' do EQUIPMENT.each { |k, v| it_behaves_like 'valid class', :equipment!, k, v } it_behaves_like 'invalid class', :equipment!, 'logger' end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/lib/ldap_helper_spec.rb
spec/lib/ldap_helper_spec.rb
# frozen_string_literal: true require 'spec_helper' describe LDAPHelper do def mock_ldap(user_hash) instance_spy(Net::LDAP, search: user_hash) end context 'LDAP enabled' do around(:example) do |example| env_wrapper('CAS_AUTH' => 1, 'USE_LDAP' => 1) { example.run } end describe '#search' do xit 'returns a properly formatted hash' end end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/lib/csv_export_spec.rb
spec/lib/csv_export_spec.rb
# frozen_string_literal: true require 'spec_helper' include CsvExport describe CsvExport do MODELS = [:user, :category, :equipment_model, :equipment_item].freeze PROTECTED_COLS = %w(id encrypted_password reset_password_token reset_password_sent_at).freeze shared_examples 'builds a csv' do |model| let(:csv) do generate_csv(FactoryGirl.build_list(model, 5)).split("\n") end it 'has the appropriate length' do expect(csv.size).to eq(6) end it 'has the appropriate columns' do expect(csv.first.split(',')).to \ eq(FactoryGirl.build(model).attributes.keys - PROTECTED_COLS) end it "doesn't include protected columns" do PROTECTED_COLS.each do |col| expect(csv.first.split(',')).not_to include(col) end end it 'limits columns appropriately' do cols = FactoryGirl.build(model).attributes.keys.sample(4) cols.delete 'id' if cols.include? 'id' csv = generate_csv(FactoryGirl.build_list(model, 5), cols).split("\n") expect(csv.first.split(',')).to eq(cols) end end MODELS.each { |m| it_behaves_like 'builds a csv', m } end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/lib/csv_import_spec.rb
spec/lib/csv_import_spec.rb
# frozen_string_literal: true require 'spec_helper' include CsvImport describe CsvImport do let(:parsed_csv) do [{ username: 'abc123', first_name: '', last_name: '', nickname: '', phone: '', email: '', affiliation: '' }] end context 'when CAS login is used' do context 'when only username is provided' do before do ENV['USE_PEOPLE_API'] = 'true' allow(User).to receive(:search).and_return(search_user_return) end it 'calls User.search' do described_class.import_users(parsed_csv, false, 'normal') expect(User).to have_received(:search).once end it 'populates the appropriate fields' do result = described_class .import_users(parsed_csv, false, 'normal')[:success][0] .attributes.to_h expect(result).to include(expected_user_update_hash) end end def search_user_return { cas_login: 'abc123', first_name: 'Max', last_name: 'Power', email: 'max.power@email.email', affiliation: 'STAFF', username: 'max.power@email.email' } end def expected_user_update_hash { 'username' => 'abc123', 'first_name' => 'Max', 'last_name' => 'Power', 'nickname' => '', 'phone' => nil, 'email' => 'max.power@email.email', 'affiliation' => 'STAFF', 'cas_login' => 'abc123', 'role' => 'normal' } end end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/lib/blackout_updater_spec.rb
spec/lib/blackout_updater_spec.rb
# frozen_string_literal: true require 'spec_helper' describe BlackoutUpdater do describe 'update!' do context 'without errors' do it 'successfully updates the blackout' do blackout = instance_spy(Blackout, save: true, validate: true) allow(Reservation).to receive_message_chain(:affected_by_blackout, :active).and_return([]) updater = BlackoutUpdater.new(blackout: blackout, params: {}) updater.update expect(blackout).to have_received(:save) end it 'returns success message' do blackout = instance_spy(Blackout, save: true, validate: true) allow(Reservation).to receive_message_chain(:affected_by_blackout, :active).and_return([]) updater = BlackoutUpdater.new(blackout: blackout, params: {}) results = updater.update expect(results[:result]).to eq('Blackout was successfully updated.') end it 'does not return an error' do blackout = instance_spy(Blackout, save: true, validate: true) allow(Reservation).to receive_message_chain(:affected_by_blackout, :active).and_return([]) updater = BlackoutUpdater.new(blackout: blackout, params: {}) results = updater.update expect(results[:error]).to be_nil end end context 'with errors' do context 'with conflicting reservation' do it 'does not update blackout' do blackout = instance_spy(Blackout, save: true, validate: true) cf = instance_spy('Reservation', md_link: 'Dummy conflict') allow(Reservation).to receive_message_chain(:affected_by_blackout, :active).and_return([cf]) updater = BlackoutUpdater.new(blackout: blackout, params: {}) updater.update expect(blackout).not_to have_received(:update) end it 'does not return a result' do blackout = instance_spy(Blackout, save: true, validate: true) cf = instance_spy('Reservation', md_link: 'Dummy conflict') allow(Reservation).to receive_message_chain(:affected_by_blackout, :active).and_return([cf]) updater = BlackoutUpdater.new(blackout: blackout, params: {}) results = updater.update expect(results[:result]).to be_nil end it 'returns an error' do blackout = instance_spy(Blackout, save: true, validate: true) cf = instance_spy('Reservation', md_link: 'Dummy conflict') allow(Reservation).to receive_message_chain(:affected_by_blackout, :active).and_return([cf]) updater = BlackoutUpdater.new(blackout: blackout, params: {}) results = updater.update expect(results[:error]).to include('Dummy conflict') end end context 'with invalid blackout' do it 'tries to update blackout' do blackout = instance_spy(Blackout, save: false, validate: false) allow(Reservation).to receive_message_chain(:affected_by_blackout, :active).and_return([]) allow(blackout).to receive_message_chain(:errors, :full_messages) .and_return('Dummy error message') updater = BlackoutUpdater.new(blackout: blackout, params: {}) updater.update expect(blackout).to have_received(:save) end it 'does not return a result' do blackout = instance_spy(Blackout, save: false, validate: false) allow(Reservation).to receive_message_chain(:affected_by_blackout, :active).and_return([]) allow(blackout).to receive_message_chain(:errors, :full_messages) .and_return('Dummy error message') updater = BlackoutUpdater.new(blackout: blackout, params: {}) results = updater.update expect(results[:result]).to be_nil end it 'returns an error' do blackout = instance_spy(Blackout, save: false, validate: false) allow(Reservation).to receive_message_chain(:affected_by_blackout, :active).and_return([]) allow(blackout).to receive_message_chain(:errors, :full_messages) .and_return('Dummy error message') updater = BlackoutUpdater.new(blackout: blackout, params: {}) results = updater.update expect(results[:error]).to eq('Dummy error message') end end end end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/lib/generator_spec.rb
spec/lib/generator_spec.rb
# frozen_string_literal: true require 'spec_helper' describe Generator do OBJECTS = %i[app_config category requirement user superuser].freeze shared_examples 'generates a valid' do |method| it method.to_s do expect(Generator.send(method)).to be_truthy end end OBJECTS.each { |o| it_behaves_like 'generates a valid', o } context 'blackout generation' do before { Generator.user } it_behaves_like 'generates a valid', :blackout end context 'equipment_model generation' do before { Generator.category } it_behaves_like 'generates a valid', :equipment_model end context 'requiring a category and equipment model' do before do Generator.category Generator.equipment_model end it_behaves_like 'generates a valid', :equipment_item it_behaves_like 'generates a valid', :checkout_procedure it_behaves_like 'generates a valid', :checkin_procedure end context 'reservation generation' do before do Generator.category Generator.user Generator.superuser Generator.equipment_model Generator.equipment_item end it_behaves_like 'generates a valid', :reservation end describe 'generate' do it 'creates the specified number of objects' do object = :user expect(Generator).to receive(object).exactly(5).times Generator.generate(object.to_s, 5) end end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/mailers/admin_mailer_spec.rb
spec/mailers/admin_mailer_spec.rb
# frozen_string_literal: true require 'spec_helper' shared_examples_for 'a valid admin email' do it 'sends to the admin' do expect(@mail.to.size).to eq(1) expect(@mail.to.first).to eq(AppConfig.check(:admin_email)) end it "is from no-reply@#{ActionMailer::Base.default_url_options[:host]}" do expect(@mail.from).to \ eq("no-reply@#{ActionMailer::Base.default_url_options[:host]}") end it 'should actually send the email' do expect(ActionMailer::Base.deliveries.count).to eq(1) end end describe AdminMailer, type: :mailer do before(:each) do mock_app_config(admin_email: 'admin@email.com') ActionMailer::Base.delivery_method = :test ActionMailer::Base.perform_deliveries = true ActionMailer::Base.deliveries = [] end let!(:admin) { FactoryGirl.create(:admin) } describe 'notes_reservation_notification' do before do @out = FactoryGirl.create(:checked_out_reservation) @in = FactoryGirl.create(:checked_in_reservation) @mail = AdminMailer.notes_reservation_notification([@out], [@in]).deliver_now end it 'renders the subject' do expect(@mail.subject).to\ eq('[Reservations] Notes for '\ + (Time.zone.today - 1.day).strftime('%m/%d/%y')) end it_behaves_like 'a valid admin email' end describe 'overdue_checked_in_fine_admin' do before do @model = FactoryGirl.create(:equipment_model) @item = FactoryGirl.create(:equipment_item, equipment_model: @model) @res1 = FactoryGirl.build(:checked_in_reservation, equipment_model: @model, equipment_item: @item) @res1.save(validate: false) @mail = AdminMailer.overdue_checked_in_fine_admin(@res1).deliver_now end it_behaves_like 'a valid admin email' it 'renders the subject' do expect(@mail.subject).to eq('[Reservations] Overdue equipment fine') end end describe 'overdue_checked_in_fine_admin with no fine' do before do @em = FactoryGirl.create(:equipment_model, late_fee: 0) @res = FactoryGirl.build(:checked_in_reservation, equipment_model_id: @em.id) @res.save(validate: false) @mail = AdminMailer.overdue_checked_in_fine_admin(@res).deliver_now end it 'doesn\'t send an email' do expect(ActionMailer::Base.deliveries.count).to eq(0) end end describe 'reservation_created_admin' do before do @res = FactoryGirl.create(:valid_reservation) @mail = AdminMailer.reservation_created_admin(@res).deliver_now end it_behaves_like 'a valid admin email' it 'renders the subject' do expect(@mail.subject).to eq('[Reservations] Reservation created') end end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/spec/mailers/user_mailer_spec.rb
spec/mailers/user_mailer_spec.rb
# frozen_string_literal: true require 'spec_helper' include EnvHelpers shared_examples_for 'valid user email' do it 'sends to the reserver' do expect(@mail.to.size).to eq(1) expect(@mail.to.first).to eq(reserver.email) end it 'sends an email' do expect(ActionMailer::Base.deliveries.count).to eq(1) end # FIXME: Workaround for #398 disables this functionality for RSpec testing # it "is from the admin" do # expect(@mail.from.size).to eq(1) # expect(@mail.from.first).to eq(AppConfig.check :admin_email) # end end shared_examples_for 'contains reservation' do it 'has reservation link' do # body contains link to the reservation expect(@mail.body).to \ include("<a href=\"http://0.0.0.0:3000/reservations/#{@res.id}\"") end end describe UserMailer, type: :mailer do before(:each) do @ac = mock_app_config(admin_email: 'admin@email.com', disable_user_emails: false) ActionMailer::Base.delivery_method = :test ActionMailer::Base.perform_deliveries = true ActionMailer::Base.deliveries = [] @res = FactoryGirl.create(:valid_reservation, reserver: reserver, start_date: Time.zone.today + 1) end let!(:reserver) { FactoryGirl.create(:user) } describe 'reservation_status_update' do it 'sends to the reserver' do # force a request email; there is not an email for a basic reservation @mail = UserMailer.reservation_status_update(@res, 'requested').deliver_now expect(@mail.to.size).to eq(1) expect(@mail.to.first).to eq(reserver.email) end it 'sends an email' do # force a request email; there is not an email for a basic reservation @mail = UserMailer.reservation_status_update(@res, 'requested').deliver_now expect(ActionMailer::Base.deliveries.count).to eq(1) end it 'logs if the env is set' do env_wrapper('LOG_EMAILS' => '1') do allow(Rails.logger).to receive(:info) expect(Rails.logger).to receive(:info).with(/Sent/).once # force a request email; there is not an email for a basic reservation @mail = UserMailer.reservation_status_update(@res, 'requested').deliver_now end end it "doesn't log if the env is not set" do expect(ENV['LOG_EMAILS']).to be_nil expect(Rails.logger).to receive(:info).with(/Sent/).exactly(0).times # force a request email; there is not an email for a basic reservation @mail = UserMailer.reservation_status_update(@res, 'requested').deliver_now end it 'sends denied notifications' do @res.update(status: 'denied') expect(@res.denied?).to be_truthy @mail = UserMailer.reservation_status_update(@res).deliver_now expect(@mail.subject).to \ eq("[Reservations] #{@res.equipment_model.name} Denied") end it 'sends approved request notifications' do @res.update(status: 'reserved', flags: Reservation::FLAGS[:request]) @mail = UserMailer.reservation_status_update(@res).deliver_now expect(@mail.subject).to \ eq("[Reservations] #{@res.equipment_model.name} Request Approved") end it 'sends approved request notifications for requests starting today' do @res.update(status: 'reserved', flags: Reservation::FLAGS[:request], start_date: Time.zone.today, due_date: Time.zone.today + 1) @mail = UserMailer.reservation_status_update(@res, 'request approved').deliver_now expect(@mail.subject).to \ eq("[Reservations] #{@res.equipment_model.name} Request Approved") end it 'sends expired request notifications' do @res.update(status: 'denied', flags: (Reservation::FLAGS[:request] | Reservation::FLAGS[:expired])) @mail = UserMailer.reservation_status_update(@res).deliver_now expect(@mail.subject).to \ eq("[Reservations] #{@res.equipment_model.name} Request Expired") end it 'sends reminders to check-out' do @res.update(FactoryGirl.attributes_for(:upcoming_reservation)) @mail = UserMailer.reservation_status_update(@res).deliver_now expect(@mail.subject).to \ eq("[Reservations] #{@res.equipment_model.name} Starts Today") end it 'sends missed notifications' do @res.update(FactoryGirl.attributes_for(:missed_reservation)) @mail = UserMailer.reservation_status_update(@res).deliver_now expect(@mail.subject).to \ eq("[Reservations] #{@res.equipment_model.name} Missed") end it 'sends check-out receipts' do @res.update( FactoryGirl.attributes_for(:checked_out_reservation) ) @mail = UserMailer.reservation_status_update(@res).deliver_now expect(@mail.subject).to \ eq("[Reservations] #{@res.equipment_model.name} Checked Out") end it "doesn't sends check-out receipts if not checked out" do @res.update(FactoryGirl.attributes_for(:valid_reservation)) expect(@res.checked_out).to be_nil @mail = UserMailer.reservation_status_update(@res, 'checked out').deliver_now expect(@mail).to be_nil end it 'sends check-out receipts for reservations due today' do @res.update( FactoryGirl.attributes_for(:checked_out_reservation, due_date: Time.zone.today) ) @mail = UserMailer.reservation_status_update(@res, 'checked out').deliver_now expect(@mail.subject).to \ eq("[Reservations] #{@res.equipment_model.name} Checked Out") end it 'sends check-out receipts for overdue reservations' do @res.update(FactoryGirl.attributes_for(:overdue_reservation)) @mail = UserMailer.reservation_status_update(@res, 'checked out').deliver_now expect(@mail.subject).to \ eq("[Reservations] #{@res.equipment_model.name} Checked Out") end it 'sends reminders to check-in' do @res.update( FactoryGirl.attributes_for(:checked_out_reservation, due_date: Time.zone.today) ) @mail = UserMailer.reservation_status_update(@res).deliver_now expect(@mail.subject).to \ eq("[Reservations] #{@res.equipment_model.name} Due Today") end it 'sends check-in receipts' do @res.update( FactoryGirl.attributes_for(:checked_in_reservation) ) @mail = UserMailer.reservation_status_update(@res).deliver_now expect(@mail.subject).to \ eq("[Reservations] #{@res.equipment_model.name} Returned") end it 'sends overdue equipment reminders' do @res.update(FactoryGirl.attributes_for(:overdue_reservation)) @mail = UserMailer.reservation_status_update(@res).deliver_now expect(@mail.subject).to \ eq("[Reservations] #{@res.equipment_model.name} Overdue") end it 'sends fine emails for overdue equipment' do @res.update(FactoryGirl.attributes_for(:checked_in_reservation, :overdue)) @mail = UserMailer.reservation_status_update(@res).deliver_now expect(@mail.subject).to \ eq("[Reservations] #{@res.equipment_model.name} Returned Overdue") end it "doesn't send fine emails when there is no late fee" do @res.update(FactoryGirl.attributes_for(:checked_in_reservation, :overdue)) @res.equipment_model.update(late_fee: 0) @mail = UserMailer.reservation_status_update(@res).deliver_now expect(@mail).to be_nil end it "doesn't send at all if disable_user_emails is set" do allow(@ac).to receive(:disable_user_emails).and_return(true) @mail = UserMailer.reservation_status_update(@res).deliver_now expect(@mail).to be_nil end end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/lib/csv_import.rb
lib/csv_import.rb
# frozen_string_literal: true module CsvImport # method used to convert a csv filepath to an array of objects specified by # the file def csv_import(filepath) # initialize imported_objects = [] string = File.read(filepath) require 'csv' # sanitize input string = string.encode('UTF-8', 'binary', invalid: :replace, undef: :replace, replace: '') # remove spaces from header line string = string.split(/(\r?\n)|\r/) string.first.gsub!(/\s+/, '') string.reject! { |s| /(\r?\n)|\r/.match s } string = string.join "\n" # get rid of any extra columns string.gsub!(/,,*$/, '') # import data by row CSV.parse(string, headers: true) do |row| object_hash = row.to_hash.symbolize_keys # make all nil values blank object_hash.keys.each do |key| object_hash[key] = '' if object_hash[key].nil? end imported_objects << object_hash end # return array of imported objects imported_objects end # The main import method. Pass in the array of imported objects from # csv_import, the overwrite boolean, and the user type. The safe defaults # are specified here. It first tries to save or update the user with the # data specified in the csv. If that fails, it tries ldap. If both fail, # the user is returned as part of the array of failures. def import_users(array_of_user_data, overwrite = false, user_type = 'normal') @array_of_success = [] # will contain user-objects @array_of_fail = [] # will contain user_data hashes and error messages @overwrite = overwrite array_of_user_data.each do |user_data| user_data[:role] = user_type user_data[:csv_import] = true next if attempt_save_with_csv_data?(user_data) if ENV['USE_LDAP'].present? || ENV['USE_PEOPLE_API'].present? attempt_save_with_search(user_data) else @array_of_fail << [user_data, 'Invalid user parameters.'] end end { success: @array_of_success, fail: @array_of_fail } end # attempts to import with LDAP or People, returns nil if the login is not # found, otherwise it replaces the keys in the data hash with the search data. def import_with_search(user_data) # use username if using cas, email otherwise search_param = user_data[:username] search_user_hash = User.search(login: search_param) return if search_user_hash.nil? # fill-in missing key-values with search data search_user_hash.keys.each do |key| user_data[key] = search_user_hash[key] if user_data[key].blank? end user_data end # tries to save using only the csv data. This method will return # false if the data specified in the csv is invalid on the user model. def attempt_save_with_csv_data?(user_data) if ENV['CAS_AUTH'].present? # set the cas login user_data[:cas_login] = user_data[:username] elsif user_data[:username].blank? # set the username user_data[:username] = user_data[:email] end user = set_or_create_user_for_import(user_data) # Remove nil values to avoid failing validations - we this allows us to # update role of a bunch of users by passing in only their usernames # (instead of all of their user data). data_to_update = user_data.keep_if { |_, v| v.present? } user.update(data_to_update) # if the updated or new user is valid, save to database and add to array # of successful imports return false unless user.valid? user.save @array_of_success << user true end # attempts to save a user with search lookup def attempt_save_with_search(user_data) search_hash = import_with_search(user_data) if search_hash user_data = search_hash else @array_of_fail << [user_data, 'Incomplete user information. Unable to find user '\ 'in online directory.'] return end user = set_or_create_user_for_import(user_data) if user.valid? user.save @array_of_success << user else @array_of_fail << [user_data, user.errors.full_messages.to_sentence.capitalize\ + '.'] end nil end # sets the user based on the overwrite parameter # rubocop:disable AccessorMethodName def set_or_create_user_for_import(user_data) # set the user and attempt to save with given data user = if @overwrite && !User.where('username = ?', user_data[:username]).empty? User.where('username = ?', user_data[:username]).first else User.new(user_data) end user end # rubocop:enable AccessorMethodName end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/lib/csv_export.rb
lib/csv_export.rb
# frozen_string_literal: true module CsvExport require 'csv' require 'zip' PROTECTED_COLS = %w(id encrypted_password reset_password_token reset_password_sent_at).freeze # generates a csv from the given model data # columns is optional; defaults to all columns except protected def generate_csv(data, columns = []) columns = data.first.attributes.keys if columns.empty? PROTECTED_COLS.each { |col| columns.delete(col) } CSV.generate(headers: true) do |csv| csv << columns data.each do |o| csv << columns.map do |attr| s = o.send(attr) s.is_a?(ActiveRecord::Base) ? s.name : s end end end end # generates a zip file containing multiple CSVs # expects tables to be an array of arrays with the following format: # [[objects, columns], ...] # where columns is optional; defaults to all columns except protected def generate_zip(tables) # create the CSVs csvs = tables.map { |model| generate_csv(*model) } Zip::OutputStream.write_buffer do |stream| csvs.each_with_index do |csv, i| model_name = tables[i].first.first.class.name stream.put_next_entry "#{model_name}_#{Time.zone.now.to_s(:number)}.csv" stream.write csv end end.string end # downloads a csv of the given model table # NOTE: this method depends on ActionController def download_csv(data, columns, filename) send_data(generate_csv(data, columns), filename: "#{filename}_#{Time.zone.now.to_s(:number)}.csv") end # downloads a zip file containing multiple CSVs # expects tables to be an array of arrays with the following format: # [[objects, columns], ...] # where columns is optional; defaults to all columns except protected # NOTE: this method depends on ActionController def download_zip(tables, filename) send_data(generate_zip(tables), type: 'application/zip', filename: "#{filename}.zip") end # NOTE: this method depends on ActionController def download_equipment_data(cats: Category.all, models: EquipmentModel.all, items: EquipmentItem.all) c = [cats, %w(name max_per_user max_checkout_length max_renewal_times max_renewal_length renewal_days_before_due sort_order)] m = [models, %w(category name description late_fee replacement_fee max_per_user max_renewal_length)] i = [items, %w(equipment_model name serial)] download_zip([c, m, i], "EquipmentData_#{Time.zone.now.to_s(:number)}") end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/lib/searchable.rb
lib/searchable.rb
# frozen_string_literal: true module Searchable def self.included(base) # rubocop:disable MethodLength def base.searchable_on(*args) @searchable_attrs = args end def base.catalog_search(query) if query.blank? # if the string is blank, return all active else # in all other cases, search using the query text results = [] # search each query word on each attribute specified via searchable_on query.split.each do |q| query_results = [] # this is NOT a SQL-injection so long as the attributes given to # .searchable on are not user-generated @searchable_attrs.each do |attribute| query_results << active.where("#{attribute} LIKE :query", query: "%#{q}%") end # flatten all elements associated with one query word into a 1D array query_results.flatten! # remove duplicate items in case they were added more than once # e.g. a term match in both name and description results in an item # being added twice query_results.uniq! # add this array to the over-all results results << query_results end # take the intersection of the results for each word # i.e. choose results matching all terms results.inject(:&) end end end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/lib/ldap_helper.rb
lib/ldap_helper.rb
# frozen_string_literal: true require 'net/ldap' class LDAPHelper def self.search(**params) new(**params).search end def initialize(login:) @ldap = Net::LDAP.new(conn_settings) @user_login = login end def search user_hash end private ATTRS = %i[login email first_name last_name nickname].freeze attr_reader :user_login, :ldap def user_hash # rubocop:disable Metrics/AbcSize return {} if result.empty? {}.tap do |out| out[:first_name] = result[secrets.ldap_first_name.to_sym][0] out[:last_name] = result[secrets.ldap_last_name.to_sym][0] out[:nickname] = result[secrets.ldap_nickname.to_sym][0] out[:email] = result[secrets.ldap_email.to_sym][0] # deal with affiliation out[:affiliation] = aff_params.map { |param| result[param.to_sym][0] } .select(&:present?).join(' ') # define username based on authentication method out[:username] = if ENV['CAS_AUTH'].present? result[secrets.ldap_login.to_sym][0] else out[:email] end end end def result @result ||= ldap.search(base: secrets.ldap_base, filter: filter, attributes: attrs).first end def filter @filter ||= Net::LDAP::Filter.eq(filter_param, user_login) end def filter_param ENV['CAS_AUTH'].present? ? secrets.ldap_login : secrets.ldap_email end def attrs ldap_attrs = ATTRS.map { |a| "ldap_#{a}".to_sym } @attrs ||= affilation_params + ldap_attrs.map { |a| secrets.send(a) } end def affiliation_params @aff_params ||= secrets.ldap_affiliation.split(',') @aff_params ||= [] end def secrets Rails.application.secrets end def conn_settings { host: secrets.ldap_host, port: secrets.ldap_port } end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/lib/development_mail_interceptor.rb
lib/development_mail_interceptor.rb
# frozen_string_literal: true # class DevelopmentMailInterceptor # def self.delivering_email(message) # message.subject = "[#{message.to}] #{message.subject}" # message.to = "maria.altyeva@yale.edu" # end # end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/lib/rails_extensions.rb
lib/rails_extensions.rb
# frozen_string_literal: true require 'date' class Range def intersection(other) return nil if max < other.begin || other.max < self.begin [self.begin, other.begin].max..[max, other.max].min end alias & intersection end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/lib/people_api_helper.rb
lib/people_api_helper.rb
# frozen_string_literal: true require 'json' # Helper class to handle requests to a web-service-based user profile API and # return profile data class PeopleAPIHelper # Allows for the calling of .search on the base class def self.search(**params) new(**params).search end # Initialize a new PeopleAPIHelper and generates the request object for the # web service # # @param login [String] the login value to query for def initialize(login:) @login = login @req = generate_request end # Execute an API query for profile data, returning a hash with the results if # they are found # # @return [Hash] the profile data returned by the API service def search send_request parse_response end private ATTRS = { cas_login: 'LOGIN', first_name: 'FNAME', last_name: 'LNAME', email: 'EMAIL', affiliation: 'AFF' }.freeze attr_reader :login, :req, :response def generate_request req = req_klass.new(uri) req.basic_auth api_env('USERNAME'), api_env('PASSWORD') req end def req_klass klass_name = api_env('METHOD').capitalize Net::HTTP.const_get(klass_name) end def send_request @raw ||= Net::HTTP.start(uri.host, uri.port, use_ssl: ssl?) do |http| http.request(req) end @response ||= JSON.parse(@raw.body) end def parse_response {}.tap do |out| ATTRS.each { |(attr, str)| out[attr] = extract_data(str) } out[:username] = ENV['CAS_AUTH'].present? ? out[:cas_login] : out[:email] end end def extract_data(attr) response.dig(*api_env(attr).split(',')) end def ssl? !(uri.to_s =~ /https/).nil? end def uri @uri ||= URI(full_url) end # The full request URL - either sets up a single query param with a '?' if # there aren't any in the string or appends using '&' if the URL already # contains a query param def full_url char = (api_env('URL') =~ /\?/).nil? ? '?' : '&' api_env('URL') + "#{char}#{api_env('PARAM')}=#{login}" end def api_env(str) ENV["RES_PEOPLE_API_#{str}"] end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/lib/activation_helper.rb
lib/activation_helper.rb
# frozen_string_literal: true module ActivationHelper def activate_parents(current_item) # Equipment Items have EMs and Categories that may need to be # reactivated if current_item.class == EquipmentItem # Reactivate the current item's category and/or Equipment Model if # deactivated category = Category.find( EquipmentModel.find(current_item.equipment_model_id).category_id ) category.revive if category.deleted_at em = EquipmentModel.find(current_item.equipment_model_id) if em.deleted_at em.revive # reactivate all checkin and checkout procedures if reviving an # equipment model activate_procedures(em) end # EMs have Categories and checkin/checkout procedures that may need to be # reactivated elsif current_item.class == EquipmentModel # Reactivate the current item's category category = Category.find(current_item.category_id) category.revive if category.deleted_at # Reactivate all checkin and checkout procedures activate_procedures(current_item) end end def activate_procedures(em) em.checkout_procedures.each(&:revive) em.checkin_procedures.each(&:revive) end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/lib/equipment_import.rb
lib/equipment_import.rb
# frozen_string_literal: true # rubocop:disable ModuleLength module EquipmentImport # IMPORT FUNCTIONS - these are all kinda similar, but we'll write them # separately for now and we can always refactor later. # import categories # rubocop:disable MethodLength def import_cats(processed_cats, cat_overwrite = false) # let's make sure that we're consistent w/ scope on these variables array_of_success = [] # will contain category items array_of_fail = [] # will contain category_data hashes and error messages processed_cats.each do |cat_data| cat_data[:csv_import] = true # pick or create new category based on overwrite parameter cat = if cat_overwrite && !Category.where('name = ?', cat_data[:name]).empty? Category.where('name = ?', cat_data[:name]).first else Category.new(cat_data) end cat.update(cat_data) # if updated / new category is valid, save to database and add to array # of success if cat.valid? cat.save array_of_success << cat # else, store to array of fail with error messages else array_of_fail << [cat_data, cat.errors.full_messages.to_sentence.capitalize\ + '.'] end end # return hash of status arrays { success: array_of_success, fail: array_of_fail } end # rubocop:enable MethodLength # import models # rubocop:disable MethodLength, PerceivedComplexity def import_models(processed_models, model_overwrite = false) # let's make sure that we're consistent w/ scope on these variables array_of_success = [] # will contain model items array_of_fail = [] # will contain model_data hashes and error messages processed_models.each do |model_data| model_data[:csv_import] = true # check for valid category and store id in relevant parameter (nil if # no category found) model_data[:category] = Category.where('name = ?', model_data[:category]).first # pick or create new model based on overwrite parameter model = if model_overwrite && !EquipmentModel.where('name = ?', model_data[:name]).empty? EquipmentModel.where('name = ?', model_data[:name]).first else EquipmentModel.new(model_data) end model.update(model_data) # if updated / new model is valid, save to database and add to array of # success if model.valid? model.save array_of_success << model # else, store to array of fail with error messages else error = if model_data[:category].nil? 'Category not found.' else model.errors.full_messages.to_sentence.capitalize + '.' end array_of_fail << [model_data, error] end end # return hash of status arrays { success: array_of_success, fail: array_of_fail } end # rubocop:enable MethodLength, PerceivedComplexity # import items def import_items(processed_items) # rubocop:disable MethodLength # let's make sure that we're consistent w/ scope on these variables array_of_success = [] # will contain items array_of_fail = [] # will contain item_data hashes and error messages processed_items.each do |item_data| item_data[:csv_import] = true # check for valid equipment_model and store id in relevant parameter ( # nil if no category found) item_data[:equipment_model] = EquipmentModel.where('name = ?', item_data[:equipment_model]).first # create new category item = EquipmentItem.new(item_data) item.assign_attributes(item_data) # if new item is valid, save to database and add to array of success if item.valid? item.notes = "#### Created at #{Time.zone.now.to_s(:long)} via import" item.save array_of_success << item # else, store to array of fail with error messages else error = if item_data[:equipment_model].nil? 'Equipment Model not found.' else item.errors.full_messages.to_sentence.capitalize + '.' end array_of_fail << [item_data, error] end end # return hash of status arrays { success: array_of_success, fail: array_of_fail } end # VALIDATION FUNCTIONS - not sure if this should be here or if we need to # create an import model to validate properly (see # import_equipment_controller.rb) # this is for validations that are true for all imports def valid_equipment_import?(processed_stuff, file, type, accepted_keys, key_error) # check for file unless file flash[:error] = 'Please select a file to upload' return false end # check for total CSV import failure if processed_stuff.nil? flash[:error] = "Unable to import #{type} CSV file. Please ensure it "\ 'matches the import format, and try again.' return false end # check for valid keys, ensure we don't raise a NoMethodError unless processed_stuff.first && processed_stuff.first.keys == accepted_keys flash[:error] = key_error return false end true end # these next few methods are all very similar, not sure if there's a better # way but we'll start with this. # category validators def valid_cat_import?(processed_cats, cat_file) # define accepted keys and key error # NOTE: this must match the parameters in the database / model!! accepted_keys = %i[name max_per_user max_checkout_length max_renewal_times max_renewal_length renewal_days_before_due sort_order] key_error = 'Unable to import category CSV file. Please ensure that the '\ 'first line of the file exactly matches the sample input (name, '\ 'max_per_user, etc.) Note that headers are case sensitive and must be '\ 'in the correct order.' # general validations if valid_equipment_import?(processed_cats, cat_file, 'category', accepted_keys, key_error) # custom validators for categories go here return true else return false end end # model validators def valid_model_import?(processed_models, model_file) # define accepted keys and key error accepted_keys = %i[category name description late_fee replacement_fee max_per_user max_renewal_length] key_error = 'Unable to import equipment model CSV file. Please ensure '\ 'that the first line of the file exactly matches the sample input ('\ 'category, name, etc.) Note that headers are case sensitive and must '\ 'be in the correct order.' # general validations if valid_equipment_import?(processed_models, model_file, 'equipment model', accepted_keys, key_error) # custom validators for equipment models go here return true else return false end end # item validators def valid_item_import?(processed_items, item_file) # define accepted keys and key error accepted_keys = %i[equipment_model name serial] key_error = 'Unable to import equipment item CSV file. Please ensure '\ 'that the first line of the file exactly matches the sample input ('\ 'equipment_model,name,serial) Note that headers are case sensitive '\ 'and must be in the correct order.' # general validations if valid_equipment_import?(processed_items, item_file, 'equipment item', accepted_keys, key_error) # custom validators for equipment items go here return true else return false end end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/lib/class_from_string.rb
lib/class_from_string.rb
# frozen_string_literal: true # Class for parsing strings into class names # Used in controllers to prevent SQL injection and other attacks class ClassFromString REPORTS = { 'equipment_model' => EquipmentModel, 'category' => Category, 'user' => User, 'equipment_item' => EquipmentItem }.freeze EQUIPMENT = { 'equipment_items' => EquipmentItem, 'equipment_models' => EquipmentModel, 'categories' => Category }.freeze def self.reports!(string) parse(REPORTS, string) end def self.equipment!(string) parse(EQUIPMENT, string) end def self.parse(hash, string) hash.fetch(string) end private_class_method :parse end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/lib/autocomplete.rb
lib/autocomplete.rb
# frozen_string_literal: true module Autocomplete def get_autocomplete_items(parameters) query = '%' + parameters[:term].downcase + '%' User.where( 'nickname LIKE ? OR first_name LIKE ? OR last_name LIKE ? OR username '\ "LIKE ? OR CONCAT_WS(' ',first_name,last_name) LIKE ? OR "\ "CONCAT_WS(' ',nickname,last_name) LIKE ?", query, query, query, query, query, query ) end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/lib/blackout_updater.rb
lib/blackout_updater.rb
# frozen_string_literal: true class BlackoutUpdater # Service Object to update blackouts in the blackouts controller def initialize(blackout:, params:) @blackout = blackout @blackout.assign_attributes(params) end def update return { result: nil, error: check_for_conflicts } if check_for_conflicts update_handler end private attr_reader :blackout def check_for_conflicts return unless conflicts.any? error_string end def conflicts @conflicts ||= Reservation.affected_by_blackout(@blackout).active end def error_string 'The following reservation(s) will be unable to be returned: '\ "#{conflicts_string}. Please update their due dates and try again." end def conflicts_string excess_chars = 2 s = '' conflicts.each do |conflict| s = "#{conflict.md_link}, " end s[0...-excess_chars] end def update_handler if @blackout.save { result: 'Blackout was successfully updated.', error: nil } else { result: nil, error: @blackout.errors.full_messages } end end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/lib/seed/equipment_model_generator.rb
lib/seed/equipment_model_generator.rb
# frozen_string_literal: true module EquipmentModelGenerator IMAGES = Rails.root.join('db', 'seed_images', '*') NO_PICS ||= true def self.generate EquipmentModel.create! do |em| em.name = FFaker::Product.product + ' ' + rand(1..9001).to_s em.description = FFaker::HipsterIpsum.paragraph(16) em.late_fee = rand(50.00..1000.00).round(2).to_d em.replacement_fee = rand(50.00..1000.00).round(2).to_d em.category = Category.all.sample em.max_per_user = rand(1..em.category.max_per_user) em.active = true em.max_renewal_times = rand(0..40) em.max_renewal_length = rand(0..40) em.renewal_days_before_due = rand(0..9001) em.photo = File.open(IMAGES.sample) unless NO_PICS em.associated_equipment_models = EquipmentModel.all.sample(6) end end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/lib/seed/user_generator.rb
lib/seed/user_generator.rb
# frozen_string_literal: true module UserGenerator def self.generate User.create do |u| u.first_name = FFaker::Name.first_name u.last_name = FFaker::Name.last_name u.nickname = FFaker::Name.first_name u.phone = FFaker::PhoneNumber.short_phone_number u.email = FFaker::Internet.email u.cas_login = FFaker::Internet.user_name if ENV['CAS_AUTH'].present? u.affiliation = 'YC ' + %w[BK BR CC DC ES JE MC PC SM SY TC TD].sample + ' ' + rand(2012..2015).to_s u.role = %w[normal checkout].sample u.username = ENV['CAS_AUTH'] ? u.cas_login : u.email end end def self.generate_superuser User.create! do |u| u.first_name = 'Donny' u.last_name = 'Darko' u.phone = '6666666666' u.email = 'email@email.com' u.affiliation = 'Your Mother' u.role = 'superuser' u.view_mode = 'superuser' u.username = 'dummy' u.cas_login = 'dummy' if ENV['CAS_AUTH'] end end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/lib/seed/prompted_seed.rb
lib/seed/prompted_seed.rb
# frozen_string_literal: true # rubocop:disable Rails/Output module PromptedSeed def prompted_seed prompt_app_config prompt_user generate('user') generate('category') generate('blackout') return if Category.count == 0 puts "\nThis is going to take awhile...\n" unless NO_PICS generate('equipment_model') return if EquipmentModel.count == 0 generate('equipment_item') generate('requirement') generate('checkin_procedure') generate('checkout_procedure') return if EquipmentItem.count == 0 generate('reservation') end private def generate(model) Generator.generate(model, ask_for_records(model)) end def ask_for_records(model) formatted_model = model.camelize puts "\nHow many #{formatted_model} records would you like to generate?" \ '(please enter a number)' n = STDIN.gets.chomp # set n to 0 if blank, otherwise try to convert to an int. # if that fails re-prompt n = 0 if n == '' n = Integer(n) rescue nil # rubocop:disable RescueModifier if n.nil? || n < 0 puts "Please enter a whole number\n" return ask_for_records(model) end n end def prompt_field(obj, field) puts field.to_s.split('_').collect(&:capitalize).join(' ') + ':' obj[field] = STDIN.gets.chomp begin obj.save! rescue ActiveRecord::RecordInvalid => e puts e.to_s prompt_field(obj, field) end end def prompt_password(user) puts 'Temp Password:' user.password = STDIN.noecho(&:gets).chomp user.password_confirmation = user.password begin user.save! rescue ActiveRecord::RecordInvalid => e puts e.to_s prompt_password(user) end end def prompt_user puts 'We need to create an account for you first.' \ 'Please enter the following info:' u = Generator.superuser prompt_field(u, :first_name) prompt_field(u, :last_name) prompt_field(u, :phone) prompt_field(u, :email) prompt_field(u, :affiliation) if ENV['CAS_AUTH'] prompt_field(u, :cas_login) u.username = u.cas_login u.save else u.username = u.email u.save prompt_password(u) end end def prompt_app_config ac = Generator.app_config puts 'We need to setup application settings:' prompt_field(ac, :admin_email) prompt_field(ac, :department_name) printf 'The contact form email - ' prompt_field(ac, :contact_link_location) prompt_field(ac, :home_link_text) prompt_field(ac, :home_link_location) prompt_field(ac, :site_title) end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/lib/seed/blackout_generator.rb
lib/seed/blackout_generator.rb
# frozen_string_literal: true module BlackoutGenerator def self.generate Blackout.create! do |blk| blk.start_date = rand(Time.zone.now..Time.zone.now + 1.year) blk.end_date = rand(blk.start_date..blk.start_date.next_week) blk.notice = FFaker::HipsterIpsum.paragraph(2) blk.created_by = User.first.id blk.blackout_type = %w(soft hard).sample end end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/lib/seed/reservation_generator_helper.rb
lib/seed/reservation_generator_helper.rb
# frozen_string_literal: true module ReservationGeneratorHelper include ActiveSupport::Testing::TimeHelpers def gen_res(random = false) r = Reservation.new(status: 'reserved', reserver_id: User.all.sample.id, equipment_model: EquipmentModel.all.sample, notes: FFaker::HipsterIpsum.paragraph(2), start_date: Time.zone.today) max_checkout_len = r.equipment_model.maximum_checkout_length duration = max_checkout_len - rand_val(first: 1, last: max_checkout_len - 1, default: 1, random: random) r.due_date = r.start_date + duration.days r end def make_checked_out(res, _ = false) res.status = 'checked_out' res.checked_out = res.start_date res.equipment_item = res.equipment_model.equipment_items.all.sample res.checkout_handler_id = User.where('role = ? OR role = ? OR role = ?', 'checkout', 'admin', 'superuser').all.sample.id end def make_returned(res, random = false) make_past(res, random) make_checked_out res r_date = res.due_date > Time.zone.today ? Time.zone.today : res.due_date check_in(res, rand_val(first: res.start_date, last: r_date, default: r_date, random: random)) end def make_overdue(res, random = false) make_past(res, random, true) make_checked_out res res.overdue = true end def make_returned_overdue(res, random = false) make_overdue(res, random) return_date = rand_val(first: res.due_date, last: Time.zone.today, default: Time.zone.today, random: random) check_in(res, return_date) end def make_missed(res, random = false) make_past(res, random) res.status = 'missed' end def make_archived(res, random = false) make_past(res, random) if random && rand < 0.5 res.status = 'archived' end def make_requested(res, random = false) make_future(res, random) if random && rand < 0.5 res.status = 'requested' res.flag(:request) end def make_denied(res, random = false) make_requested(res, random) res.status = 'denied' end def check_in(res, date) res.status = 'returned' res.checked_in = date res.checkin_handler_id = User.where('role = ? OR role = ? OR role = ?', 'checkout', 'admin', 'superuser').all.sample.id end def make_past(res, random = false, overdue = false) start = overdue ? res.duration.days : 1.day past = - rand_val(first: start, last: 1.year, default: start + 1.week, random: random) offset(res, past) # save on the start date so validations run properly travel_to(res.start_date) { res.save } end def make_future(res, random = false) # set the amount of time in the future future = rand_val(first: 1.day, last: 3.months, default: 1.week, random: random) offset(res, future) end def offset(res, size) len = res.duration.days res.start_date = res.start_date.days_since(size) res.due_date = res.start_date + len end def rand_val(first:, last:, default:, random: false) return default unless random rand(first..last) end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/lib/seed/requirement_generator.rb
lib/seed/requirement_generator.rb
# frozen_string_literal: true module RequirementGenerator def self.generate Requirement.create! do |req| req.equipment_models = EquipmentModel.all.sample(rand(1..3)) req.contact_name = FFaker::Name.name req.contact_info = FFaker::PhoneNumber.short_phone_number req.notes = FFaker::HipsterIpsum.paragraph(4) req.description = FFaker::HipsterIpsum.sentence end end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/lib/seed/equipment_item_generator.rb
lib/seed/equipment_item_generator.rb
# frozen_string_literal: true module EquipmentItemGenerator def self.generate EquipmentItem.create! do |ei| ei.name = "Number #{(0...3).map { 65.+(rand(25)).chr }.join}" + rand(1..9001).to_s ei.serial = (0...8).map { 65.+(rand(25)).chr }.join ei.active = true ei.equipment_model_id = EquipmentModel.all.sample.id ei.notes = '' end end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/lib/seed/category_generator.rb
lib/seed/category_generator.rb
# frozen_string_literal: true module CategoryGenerator def self.generate Category.create! do |c| category_name = FFaker::Product.brand category_names = Category.all.to_a.map!(&:name) # Verify uniqueness of category name while category_names.include?(category_name) category_name = FFaker::Product.brand end c.name = category_name c.max_per_user = rand(1..40) c.max_checkout_length = rand(1..40) c.sort_order = rand(100) c.max_renewal_times = rand(0..40) c.max_renewal_length = rand(0..40) c.renewal_days_before_due = rand(0..9001) end end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/lib/seed/procedure_generator.rb
lib/seed/procedure_generator.rb
# frozen_string_literal: true module ProcedureGenerator def self.generate_checkin CheckinProcedure.create!(attributes) end def self.generate_checkout CheckoutProcedure.create!(attributes) end def self.attributes { step: FFaker::HipsterIpsum.sentence, equipment_model_id: EquipmentModel.all.sample.id } end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/lib/seed/automatic_seed.rb
lib/seed/automatic_seed.rb
# frozen_string_literal: true # rubocop:disable Rails/Output module AutomaticSeed def automatic_seed start_time = Time.zone.now puts 'Seeding the database automatically, without images...' Generator.app_config create_superuser Generator.generate('user', 25) Generator.generate('category', 10) Generator.generate('equipment_model', 25) Generator.generate('equipment_item', 50) Generator.generate('checkin_procedure', 3) Generator.generate('checkout_procedure', 3) generate_all_reservation_types Generator.generate('reservation', 3) puts "Successfully seeded all records! (#{Time.zone.now - start_time}s)\n\n" return if ENV['CAS_AUTH'].present? puts "You can log in using e-mail 'email@email.com' and "\ "password 'passw0rd'" end private def generate_all_reservation_types puts 'Generating reservations at each point in the lifecycle' Generator.all_reservation_types end def create_superuser u = Generator.superuser if ENV['CAS_AUTH'].present? prompt_field(u, :cas_login) u.username = u.cas_login else u.username = u.email u.password = 'passw0rd' u.password_confirmation = u.password end u.save end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/lib/seed/app_config_generator.rb
lib/seed/app_config_generator.rb
# frozen_string_literal: true module AppConfigGenerator DEFAULT_MSGS = File.join(Rails.root, 'db', 'default_messages') TOS_TEXT = File.read(File.join(DEFAULT_MSGS, 'tos_text')) UPCOMING_CHECKIN_RES_EMAIL = File.read(File.join(DEFAULT_MSGS, 'upcoming_checkin_email')) UPCOMING_CHECKOUT_RES_EMAIL = File.read(File.join(DEFAULT_MSGS, 'upcoming_checkout_email')) OVERDUE_RES_EMAIL_BODY = File.read(File.join(DEFAULT_MSGS, 'overdue_email')) DELETED_MISSED_RES_EMAIL = File.read(File.join(DEFAULT_MSGS, 'deleted_missed_email')) def self.generate return AppConfig.first if AppConfig.first AppConfig.create! do |ac| ac.terms_of_service = TOS_TEXT ac.reservation_confirmation_email_active = false ac.overdue_checkin_email_active = false ac.site_title = 'Reservations' ac.upcoming_checkin_email_active = false ac.notify_admin_on_create = false ac.admin_email = 'admin@admin.com' ac.department_name = 'Department' ac.contact_link_location = 'contact@admin.com' ac.home_link_text = 'home_link' ac.home_link_location = 'Canada' ac.deleted_missed_reservation_email_body = DELETED_MISSED_RES_EMAIL ac.default_per_cat_page = 10 ac.request_text = '' ac.upcoming_checkin_email_body = UPCOMING_CHECKIN_RES_EMAIL ac.upcoming_checkout_email_body = UPCOMING_CHECKOUT_RES_EMAIL ac.overdue_checkin_email_body = OVERDUE_RES_EMAIL_BODY end end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/lib/seed/generator.rb
lib/seed/generator.rb
# frozen_string_literal: true # rubocop:disable Rails/Output module Generator require 'ffaker' require 'ruby-progressbar' PROGRESS_STR = '%t: [%B] %P%% | %c / %C | %E' def self.generate(obj, n) return if n == 0 puts "Generating #{n} #{obj.camelize}...\n" progress = ProgressBar.create(format: PROGRESS_STR, total: n) n.times do send(obj) progress.increment end end def self.all_reservation_types ReservationGenerator.generate_all_types end def self.app_config AppConfigGenerator.generate end def self.blackout BlackoutGenerator.generate end def self.category CategoryGenerator.generate end def self.checkin_procedure ProcedureGenerator.generate_checkin end def self.checkout_procedure ProcedureGenerator.generate_checkout end def self.equipment_model EquipmentModelGenerator.generate end def self.equipment_item EquipmentItemGenerator.generate end def self.requirement RequirementGenerator.generate end def self.reservation ReservationGenerator.generate_random end def self.user UserGenerator.generate end def self.superuser UserGenerator.generate_superuser end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/lib/seed/reservation_generator.rb
lib/seed/reservation_generator.rb
# frozen_string_literal: true module ReservationGenerator extend ReservationGeneratorHelper RES_TYPES = Reservation.statuses.keys + %w[future overdue returned_overdue] - %w[reserved] # Generate one of each reservation type with fixed time differences and # one with random time differences def self.generate_all_types RES_TYPES.each do |t| attempt_res_gen(t) attempt_res_gen(t, true) end end # Generate random reservation def self.generate_random attempt_res_gen(RES_TYPES.sample, true) end def self.attempt_res_gen(type, random = false) 50.times do res = gen_res(random) send("make_#{type}".to_sym, res, random) begin res.save! # save the equipment model for the counter cache updates res.equipment_model.save return res rescue res.delete end end end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/lib/extras/simple_form_extensions.rb
lib/extras/simple_form_extensions.rb
# frozen_string_literal: true module ButtonComponents def submit_button(*args, &block) options = args.extract_options! options[:class] = ['btn-primary', options[:class]].compact args << options # rubocop:disable AssignmentInCondition if cancel = options.delete(:cancel) submit(*args, &block) + ' ' + template.link_to( template.button_tag(I18n.t('simple_form.buttons.cancel'), type: 'button', class: 'btn btn-default'), cancel ) else submit(*args, &block) end # rubocop:enable AssignmentInCondition end end SimpleForm::FormBuilder.send :include, ButtonComponents
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/lib/job_helpers/email_job_helper.rb
lib/job_helpers/email_job_helper.rb
# frozen_string_literal: true module EmailJobHelper private def send_email(res) UserMailer.reservation_status_update(res).deliver_now end def log_email(res) Rails.logger.info "Sending reminder for #{res.human_status} reservation:\n \ #{res.inspect}" end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/config/application.rb
config/application.rb
# frozen_string_literal: true require_relative 'boot' require 'active_storage/engine' require 'rails/all' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups(:default, Rails.env)) module Reservations class Application < Rails::Application # 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. # Custom directories with classes and modules you want to be autoloadable. config.eager_load_paths += %w[/lib/extras /lib/seed /lib/job_helpers /lib/].map { |s| "#{config.root}#{s}" } config.watchable_dirs['lib'] = [:rb] # 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. # Default is UTC. config.time_zone = 'Eastern Time (US & Canada)' # 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}').to_s] # config.i18n.default_locale = :de # JavaScript files you want as :defaults (application.js is always # included). # config.action_view.javascript_expansions[:defaults] = %w(jquery rails) # Configure the default encoding used in templates for Ruby 1.9. config.encoding = 'utf-8' # Configure sensitive parameters which will be filtered from the log file. config.filter_parameters += [:password] # config.rubycas.cas_base_url = 'https://secure.its.yale.edu/cas/' # Enable the asset pipeline config.assets.enabled = true # Version of your assets, change this if you want to expire all your assets config.assets.version = '1.0' # Change the path that assets are served from # config.assets.prefix = "/assets" # Add app/assets/fonts to the asset pipeline known paths config.assets.paths << Rails.root.join('app', 'assets', 'fonts') # Load all helpers in all views config.action_controller.include_all_helpers = true # set up routing options for Reports (at a minimum) config.after_initialize do Rails.application.routes.default_url_options = config.action_mailer.default_url_options end end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/config/environment.rb
config/environment.rb
# frozen_string_literal: true # Load the Rails application. require 'rails_extensions' require_relative 'application' # Version variable if Dir.exist?('.git/') && !defined? APP_VERSION APP_VERSION = `git describe --tags --abbrev=0`.strip end unless defined? APP_VERSION File.open('CHANGELOG.md', 'r') do |f| while line = f.gets # rubocop:disable AssignmentInCondition version = line[/v[0-9]+\.[0-9]+\.[0-9]+/] if version APP_VERSION = version break end end end end # Initialize the rails application Reservations::Application.initialize!
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/config/puma.rb
config/puma.rb
# frozen_string_literal: true # Puma can serve each request in a thread from an internal thread pool. # The `threads` method setting takes two numbers: a minimum and maximum. # Any libraries that use thread pools should be configured to match # the maximum value specified for Puma. Default is set to 5 threads for minimum # and maximum; this matches the default thread size of Active Record. # max_threads_count = ENV.fetch('RAILS_MAX_THREADS') { 5 } min_threads_count = ENV.fetch('RAILS_MIN_THREADS') { max_threads_count } threads min_threads_count, max_threads_count # Specifies the `port` that Puma will listen on to receive requests; # default is 3000. # port ENV.fetch('PORT') { 3000 } # Specifies the `environment` that Puma will run in. # environment ENV.fetch('RAILS_ENV') { 'development' } # Specifies the `pidfile` that Puma will use. pidfile ENV.fetch('PIDFILE') { 'tmp/pids/server.pid' } # Specifies the number of `workers` to boot in clustered mode. # Workers are forked web server processes. If using threads and workers together # the concurrency of the application would be max `threads` * `workers`. # Workers do not work on JRuby or Windows (both of which do not support # processes). # # workers ENV.fetch("WEB_CONCURRENCY") { 2 } # Use the `preload_app!` method when specifying a `workers` number. # This directive tells Puma to first boot the application and load code # before forking the application. This takes advantage of Copy On Write # process behavior so workers use less memory. # # preload_app! # Allow puma to be restarted by `rails restart` command. plugin :tmp_restart
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/config/routes.rb
config/routes.rb
# frozen_string_literal: true Reservations::Application.routes.draw do root to: 'catalog#index' # routes for Devise devise_scope :user do devise_for :users end mount RailsAdmin::Engine => '/admin', as: 'rails_admin' ## Concerns concern :deactivatable do member do put :deactivate put :activate end end concern :calendarable do member { get :calendar } end resources :documents, :requirements resources :equipment_items, concerns: %i[deactivatable calendarable] resources :announcements, except: [:show] resources :categories, concerns: %i[deactivatable calendarable] do resources :equipment_models, concern: :calendarable end resources :equipment_models, concerns: %i[deactivatable calendarable] do collection do put 'update_catalog_cart' delete 'empty_cart' end resources :equipment_items, concerns: :calendarable end get 'equipment_objects', to: redirect('equipment_items') get 'equipment_objects/:id', to: redirect('equipment_items/%<id>') get '/import_users/import', to: 'import_users#import_page', as: :csv_import_page post '/import_users/imported', to: 'import_users#import', as: :csv_imported get '/import_equipment/import', to: 'import_equipment#import_page', as: :equip_import_page post '/import_equipment/imported', to: 'import_equipment#import', as: :equip_imported resources :users, concerns: :calendarable do collection do post :find post :quick_new post :quick_create end member do put :ban put :unban delete :empty_cart end get :autocomplete_user_last_name, on: :collection end get '/catalog/search', to: 'catalog#search', as: :catalog_search get '/markdown_help', to: 'application#markdown_help', as: :markdown_help resources :reservations do member do get :send_receipt put :renew put :archive end end # reservations views get '/reservations/manage/:user_id', to: 'reservations#manage', as: :manage_reservations_for_user get '/reservations/current/:user_id', to: 'reservations#current', as: :current_reservations_for_user get '/reservations/review/:id', to: 'reservations#review', as: :review_request put '/reservations/approve/:id', to: 'reservations#approve_request', as: :approve_request put '/reservations/deny/:id', to: 'reservations#deny_request', as: :deny_request # reservation checkout / check-in actions put '/reservations/checkout/:user_id', to: 'reservations#checkout', as: :checkout put '/reservations/check-in/:user_id', to: 'reservations#checkin', as: :checkin get '/blackouts/flash_message', to: 'blackouts#flash_message', as: :flash_message get '/blackouts/new_recurring', to: 'blackouts#new_recurring', as: :new_recurring_blackout put '/reservation/update_index_dates', to: 'reservations#update_index_dates', as: :update_index_dates put '/reservation/view_all_dates', to: 'reservations#view_all_dates', as: :view_all_dates resources :blackouts do collection do post :create_recurring end member do get :flash_message delete :destroy_recurring end end put '/catalog/update_view', to: 'catalog#update_user_per_cat_page', as: :update_user_per_cat_page get '/catalog', to: 'catalog#index', as: :catalog put '/add_to_cart/:id', to: 'catalog#add_to_cart', as: :add_to_cart put '/remove_from_cart/:id', to: 'catalog#remove_from_cart', as: :remove_from_cart put '/catalog/edit_cart_item/:id', to: 'catalog#edit_cart_item', as: :edit_cart_item post '/catalog/submit_cart_updates_form/:id', to: 'catalog#submit_cart_updates_form', as: :submit_cart_updates put '/catalog/reload_catalog_cart', to: 'catalog#reload_catalog_cart', as: :reload_catalog_cart put '/catalog/change_reservation_dates', to: 'catalog#change_reservation_dates', as: :change_reservations_dates delete '/catalog/empty_cart', to: 'catalog#empty_cart', as: :catalog_empty_cart get '/reports/index', to: 'reports#index', as: :reports get '/reports/subreport/:class/:id', to: 'reports#subreport', as: :subreport put '/reports/update', to: 'reports#update_dates', as: :update_dates get '/terms_of_service', to: 'application#terms_of_service', as: :tos # yes, both of these are needed to override rails defaults of # /controller/:id/edit get '/app_configs/', to: 'app_configs#edit', as: :edit_app_configs # match resources :app_configs, only: %i[update] do collection do put :run_hourly_tasks put :run_daily_tasks end end get '/new_admin_user', to: 'application_setup#new_admin_user', as: :new_admin_user post '/create_admin_user', to: 'application_setup#create_admin_user', as: :create_admin_user resources :application_setup, only: %i[new_admin_user create_admin_user] get '/new_app_configs', to: 'application_setup#new_app_configs', as: :new_app_configs post '/create_app_configs', to: 'application_setup#create_app_configs', as: :create_app_configs put '/reload_catalog_cart', to: 'application#reload_catalog_cart', as: :reload_cart delete '/empty_cart', to: 'application#empty_cart', as: :empty_cart get 'contact', to: 'contact#new', as: 'contact_us' post 'contact', to: 'contact#create', as: 'contact_submitted' get 'announcements/:id/hide', to: 'announcements#hide', as: 'hide_announcement' get 'status', to: 'status#index' get 'status/index' # this is a fix for running letter opener inside vagrant mount LetterOpenerWeb::Engine, at: '/letter_opener' if Rails.env.development? end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/config/deploy.rb
config/deploy.rb
# config valid only for Capistrano 3.1 lock '3.8.2' set :application, "reservations-#{ENV['IDENTIFIER']}" set :repo_url, 'https://github.com/YaleSTC/reservations.git' # Default branch is :master set :branch, "#{ENV['GIT_TAG']}" # Default deploy_to directory is /var/www/my_app set :deploy_to, "#{ENV['DEPLOY_DIR']}" set :param_file, "#{ENV['PARAM_FILE']}" # Set Rails environment # set, :rails_env, 'production' # Set rvm stuff set :rvm_ruby_version, File.read('.ruby-version').strip # Default value for :scm is :git # set :scm, :git # Default value for :format is :pretty # set :format, :pretty # Default value for :log_level is :debug # set :log_level, :debug # Default value for :pty is false # set :pty, true # Default value for :linked_files is [] # set :linked_files, %w{config/database.yml} # Default value for linked_dirs is [] set :linked_dirs, %w{log public/system public/attachments vendor/bundle} # Default value for default_env is {} # set :default_env, { path: "/opt/ruby/bin:$PATH" } # Default value for keep_releases is 5 # set :keep_releases, 5 namespace :deploy do desc 'Restart application' task :restart do on roles(:app), in: :sequence, wait: 5 do execute :touch, release_path.join('tmp/restart.txt') end end before :updated, 'config:env' before :updated, 'config:db' before :updated, 'config:secrets' before :updated, 'config:party_foul' after :publishing, :restart end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/config/spring.rb
config/spring.rb
# frozen_string_literal: true Spring.watch( '.ruby-version', '.rbenv-vars', 'tmp/restart.txt', 'tmp/caching-dev.txt' )
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/config/unicorn.rb
config/unicorn.rb
# frozen_string_literal: true # rubocop:disable Rails/Output worker_processes Integer(ENV['WEB_CONCURRENCY'] || 3) timeout 15 preload_app true before_fork do |_server, _worker| Signal.trap 'TERM' do puts 'Unicorn master intercepting TERM and sending myself QUIT instead' Process.kill 'QUIT', Process.pid end defined?(ActiveRecord::Base) and # rubocop:disable AndOr ActiveRecord::Base.connection.disconnect! end after_fork do |_server, _worker| Signal.trap 'TERM' do puts 'Unicorn worker intercepting TERM and doing nothing. Wait for '\ 'master to send QUIT' end defined?(ActiveRecord::Base) and # rubocop:disable AndOr ActiveRecord::Base.establish_connection end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/config/boot.rb
config/boot.rb
# frozen_string_literal: true ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__) require 'bundler/setup' # Set up gems listed in the Gemfile. require 'bootsnap/setup' # Speed up boot time by caching expensive operations.
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/config/schedule.rb
config/schedule.rb
# frozen_string_literal: true # Use this file to easily define all of your cron jobs. # # It's helpful, but not entirely necessary to understand cron before proceeding. # http://en.wikipedia.org/wiki/Cron # For Heroku deployments, this will be superseded by the Heroku scheduler (for # more info see: https://devcenter.heroku.com/articles/scheduler). # Any changes here should be implemented in lib/tasks/scheduler.rake! # Example: # # set :cron_log, "/path/to/my/cron_log.log" # # every 2.hours do # command "/usr/bin/some_great_command" # runner "MyModel.some_method" # rake "some:great:rake:task" # end # # every 4.days do # runner "AnotherModel.prune_old_records" # end # Learn more: http://github.com/javan/whenever # Add all set environment variables to Crontab ENV.each_key do |key| env key.to_sym, ENV[key] end # Log to stdout set :output, "/var/log/cron.log" # Overwrite rake job_type to not include --silent flag job_type :rake, "cd :path && :environment_variable=:environment bundle exec rake :task :output" # Set environment set :environment, ENV["RAILS_ENV"] # every night around 5 AM EST every :day, at: '12:00am' do rake 'run_daily_tasks' end # every hour (except five AM) every :hour do rake 'run_hourly_tasks' end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/config/initializers/content_security_policy.rb
config/initializers/content_security_policy.rb
# frozen_string_literal: true # Be sure to restart your server when you modify this file. # Define an application-wide content security policy # For further information see the following documentation # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy # Rails.application.config.content_security_policy do |policy| # policy.default_src :self, :https # policy.font_src :self, :https, :data # policy.img_src :self, :https, :data # policy.object_src :none # policy.script_src :self, :https # policy.style_src :self, :https # # If you are using webpack-dev-server then specify webpack-dev-server host # if Rails.env.development? # policy.connect_src :self # :https, "http://localhost:3035", # "ws://localhost:3035" # end # # Specify URI for violation reports # # policy.report_uri "/csp-violation-report-endpoint" # end # If you are using UJS then enable automatic nonce generation # Rails.application.config.content_security_policy_nonce_generator = # -> request { SecureRandom.base64(16) } # Set the nonce only to specific directives # Rails.application.config.content_security_policy_nonce_directives = # %w(script-src) # Report CSP violations to a specified URI # For further information see the following documentation: # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy-Report-Only # Rails.application.config.content_security_policy_report_only = true
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/config/initializers/filter_parameter_logging.rb
config/initializers/filter_parameter_logging.rb
# frozen_string_literal: true # Be sure to restart your server when you modify this file. # Configure sensitive parameters which will be filtered from the log file. Rails.application.config.filter_parameters += [:password]
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/config/initializers/authentication.rb
config/initializers/authentication.rb
# frozen_string_literal: true # Check for authentication method and copy data over if necessary (ENV variable # to skip if necessary, skip if migrating from a pre-v4.1.0 DB or no table) unless ENV['SKIP_AUTH_INIT'] || !User.table_exists? || !User.column_names.include?('username') user = User.first # if we want to use CAS authentication and the username parameter doesn't # match the cas_login parameter, we need to copy that over if ENV['CAS_AUTH'].present? && user && (user.username != user.cas_login) # if there are any users that don't have cas_logins, we can't use CAS if User.where(cas_login: ['', nil]).count.positive? raise 'There are users missing their CAS logins, you cannot use CAS '\ 'authentication.' else User.all.each { 'username = cas_login' } end # if we want to use password authentication all users can reset their # passwords so it doesn't matter if they already have them or not elsif ENV['CAS_AUTH'].nil? && user && (user.username != user.email) User.all.each { 'username = email' } end end
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/config/initializers/session_store.rb
config/initializers/session_store.rb
# frozen_string_literal: true # Be sure to restart your server when you modify this file. Rails.application.config.session_store :cookie_store, key: '_reservations_session'
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false
YaleSTC/reservations
https://github.com/YaleSTC/reservations/blob/2d5f0b2511a50787d79023bb3bbd148160dc3cc2/config/initializers/days_of_the_week.rb
config/initializers/days_of_the_week.rb
# frozen_string_literal: true # rubocop:disable UselessAssignment def days_of_the_week_long days_of_the_week_long = %w(Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday) end def days_of_the_week_short days_of_the_week_short = %w(Sun, Mon, Tues, Wed, Thurs, Fri, Sat) end def days_of_the_week_short_with_index days_of_the_week_short_with_index = [[0, 'Sun'], [1, 'Mon'], [2, 'Tues'], [3, 'Wed'], [4, 'Thurs'], [5, 'Fri'], [6, 'Sat']] end # rubocop:enable UselessAssignment
ruby
MIT
2d5f0b2511a50787d79023bb3bbd148160dc3cc2
2026-01-04T17:43:15.442188Z
false