# typed: false # frozen_string_literal: true require "spec_helper" RSpec.describe "loading optimizations" do context "cars table" do before do Car.create!(name: "Toyota Camry", fuel_type: "gasoline", engine_size: 2.0) Car.create!(name: "Toyota Prius", fuel_type: "hybrid", engine_size: 1.5) Car.create!( name: "Toyota Corolla", fuel_type: "electric", engine_size: 1.8 ) end shared_examples "queries only the aux table" do it "queries only the aux table" do expect(@queries.length).to eq(1) expect(@queries.first).not_to include("JOIN") expect(@queries.first).to match(/\bvehicles_car_aux\b/) expect(@queries.first).not_to match(/\bvehicles\b/) end end shared_examples "queries both tables" do it "queries both tables" do expect(@queries.length).to eq(1) expect(@queries.first).to include("JOIN") expect(@queries.first).to match(/\bvehicles\b/) expect(@queries.first).to match(/\bvehicles_car_aux\b/) end end describe "pluck" do context "aux columns are referenced" do before do @queries = SpecHelper.capture_queries do expect(Car.pluck(:fuel_type)).to eq(%w[gasoline hybrid electric]) end end it_behaves_like "queries only the aux table" end context "aux columns are chained on a where clause" do before do @queries = SpecHelper.capture_queries do expect(Car.where(engine_size: 1.4..1.9).pluck(:fuel_type)).to eq( %w[hybrid electric] ) end end it_behaves_like "queries only the aux table" it "applies the BETWEEN clause" do expect(@queries.first).to include("BETWEEN") end end context "main table columns are referenced" do before do @queries = SpecHelper.capture_queries do expect(Car.where(name: "Toyota Camry").pluck(:fuel_type)).to eq( %w[gasoline] ) end end it_behaves_like "queries both tables" end context "main table columns are chained on a where clause" do before do @queries = SpecHelper.capture_queries do expect(Car.where(name: "Toyota Camry").pluck(:fuel_type)).to eq( %w[gasoline] ) end end it_behaves_like "queries both tables" end end describe "maximum" do context "aux columns are referenced" do before do @queries = SpecHelper.capture_queries do expect(Car.maximum(:engine_size)).to eq(2.0) end end it_behaves_like "queries only the aux table" end context "aux columns are chained on a where clause" do before do @queries = SpecHelper.capture_queries do expect( Car.where(engine_size: 1.4..1.9).maximum(:engine_size) ).to eq(1.8) end end it_behaves_like "queries only the aux table" end context "main table columns are referenced" do before do @queries = SpecHelper.capture_queries do expect( Car.where(name: "Toyota Camry").maximum(:engine_size) ).to eq(2.0) end end it_behaves_like "queries both tables" end context "main table columns are chained on a where clause" do before do @queries = SpecHelper.capture_queries do expect( Car.where(name: "Toyota Camry").maximum(:engine_size) ).to eq(2.0) end end it_behaves_like "queries both tables" end end end end