diff --git a/.rspec b/.rspec new file mode 100644 index 00000000..c99d2e73 --- /dev/null +++ b/.rspec @@ -0,0 +1 @@ +--require spec_helper diff --git a/Gemfile b/Gemfile index e20b1260..3002f03d 100644 --- a/Gemfile +++ b/Gemfile @@ -3,24 +3,33 @@ git_source(:github) { |repo| "https://github.com/#{repo}.git" } ruby '2.6.3' -gem 'rails', '~> 5.2.3' +gem 'activerecord-import' +gem 'bootsnap', '>= 1.1.0', require: false +gem 'oj' gem 'pg', '>= 0.18', '< 2.0' gem 'puma', '~> 3.11' -gem 'bootsnap', '>= 1.1.0', require: false - +gem 'rails', '~> 5.2.3' group :development, :test do # Call 'byebug' anywhere in the code to stop execution and get a debugger console - gem 'byebug', platforms: [:mri, :mingw, :x64_mingw] + gem 'bullet' + gem 'byebug', platforms: %i[mri mingw x64_mingw] + gem 'memory_profiler' + gem 'rspec-rails' + gem 'rspec-benchmark' + gem 'ruby-prof' + gem 'ruby-progressbar' end - group :development do + gem 'meta_request' # Access an interactive console on exception pages or by calling 'console' anywhere in the code. - gem 'web-console', '>= 3.3.0' gem 'listen', '>= 3.0.5', '< 3.2' + gem 'web-console', '>= 3.3.0' end - +gem 'pghero' +gem 'pg_query', '>= 2' +gem 'rack-mini-profiler', require: false group :test do end # Windows does not include zoneinfo files, so bundle the tzinfo-data gem -gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby] +gem 'tzinfo-data', platforms: %i[mingw mswin x64_mingw jruby] diff --git a/Gemfile.lock b/Gemfile.lock index fccf6f5f..2ac1a7fe 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -33,6 +33,8 @@ GEM activemodel (= 5.2.3) activesupport (= 5.2.3) arel (>= 9.0) + activerecord-import (1.5.0) + activerecord (>= 4.2) activestorage (5.2.3) actionpack (= 5.2.3) activerecord (= 5.2.3) @@ -43,17 +45,25 @@ GEM minitest (~> 5.1) tzinfo (~> 1.1) arel (9.0.0) + benchmark-malloc (0.2.0) + benchmark-perf (0.6.0) + benchmark-trend (0.4.0) bindex (0.6.0) bootsnap (1.4.2) msgpack (~> 1.0) builder (3.2.3) + bullet (7.1.3) + activesupport (>= 3.0.0) + uniform_notifier (~> 1.11) byebug (11.0.1) concurrent-ruby (1.1.5) crass (1.0.4) + diff-lcs (1.5.0) erubi (1.8.0) ffi (1.10.0) globalid (0.4.2) activesupport (>= 4.2.0) + google-protobuf (3.23.4) i18n (1.6.0) concurrent-ruby (~> 1.0) listen (3.1.5) @@ -67,8 +77,14 @@ GEM mini_mime (>= 0.1.1) marcel (0.3.3) mimemagic (~> 0.3.2) + memory_profiler (1.0.1) + meta_request (0.7.4) + rack-contrib (>= 1.1, < 3) + railties (>= 3.0.0, < 7.1) method_source (0.9.2) - mimemagic (0.3.3) + mimemagic (0.3.10) + nokogiri (~> 1) + rake mini_mime (1.0.1) mini_portile2 (2.4.0) minitest (5.11.3) @@ -76,9 +92,18 @@ GEM nio4r (2.3.1) nokogiri (1.10.2) mini_portile2 (~> 2.4.0) + oj (3.14.2) pg (1.1.4) + pg_query (4.2.3) + google-protobuf (>= 3.22.3) + pghero (2.8.3) + activerecord (>= 5) puma (3.12.1) rack (2.0.6) + rack-contrib (2.4.0) + rack (< 4) + rack-mini-profiler (3.1.1) + rack (>= 1.2.0) rack-test (1.1.0) rack (>= 1.0, < 3) rails (5.2.3) @@ -109,6 +134,34 @@ GEM rb-fsevent (0.10.3) rb-inotify (0.10.0) ffi (~> 1.0) + rspec (3.12.0) + rspec-core (~> 3.12.0) + rspec-expectations (~> 3.12.0) + rspec-mocks (~> 3.12.0) + rspec-benchmark (0.6.0) + benchmark-malloc (~> 0.2) + benchmark-perf (~> 0.6) + benchmark-trend (~> 0.4) + rspec (>= 3.0) + rspec-core (3.12.2) + rspec-support (~> 3.12.0) + rspec-expectations (3.12.3) + diff-lcs (>= 1.2.0, < 2.0) + rspec-support (~> 3.12.0) + rspec-mocks (3.12.6) + diff-lcs (>= 1.2.0, < 2.0) + rspec-support (~> 3.12.0) + rspec-rails (5.1.2) + actionpack (>= 5.2) + activesupport (>= 5.2) + railties (>= 5.2) + rspec-core (~> 3.10) + rspec-expectations (~> 3.10) + rspec-mocks (~> 3.10) + rspec-support (~> 3.10) + rspec-support (3.12.1) + ruby-prof (1.4.3) + ruby-progressbar (1.13.0) ruby_dep (1.5.0) sprockets (3.7.2) concurrent-ruby (~> 1.0) @@ -121,6 +174,7 @@ GEM thread_safe (0.3.6) tzinfo (1.2.5) thread_safe (~> 0.1) + uniform_notifier (1.16.0) web-console (3.7.0) actionview (>= 5.0) activemodel (>= 5.0) @@ -134,12 +188,24 @@ PLATFORMS ruby DEPENDENCIES + activerecord-import bootsnap (>= 1.1.0) + bullet byebug listen (>= 3.0.5, < 3.2) + memory_profiler + meta_request + oj pg (>= 0.18, < 2.0) + pg_query (>= 2) + pghero puma (~> 3.11) + rack-mini-profiler rails (~> 5.2.3) + rspec-benchmark + rspec-rails + ruby-prof + ruby-progressbar tzinfo-data web-console (>= 3.3.0) diff --git a/app/controllers/trips_controller.rb b/app/controllers/trips_controller.rb index acb38be2..7acb2f7c 100644 --- a/app/controllers/trips_controller.rb +++ b/app/controllers/trips_controller.rb @@ -2,6 +2,6 @@ class TripsController < ApplicationController def index @from = City.find_by_name!(params[:from]) @to = City.find_by_name!(params[:to]) - @trips = Trip.where(from: @from, to: @to).order(:start_time) + @trips = Trip.includes(bus: :services).where(from: @from, to: @to).order(:start_time).load end end diff --git a/app/models/bus.rb b/app/models/bus.rb index 1dcc54cb..d97de31f 100644 --- a/app/models/bus.rb +++ b/app/models/bus.rb @@ -13,7 +13,8 @@ class Bus < ApplicationRecord ].freeze has_many :trips - has_and_belongs_to_many :services, join_table: :buses_services + has_many :buses_services + has_many :services, through: :buses_services validates :number, presence: true, uniqueness: true validates :model, inclusion: { in: MODELS } diff --git a/app/models/buses_service.rb b/app/models/buses_service.rb new file mode 100644 index 00000000..6219d44e --- /dev/null +++ b/app/models/buses_service.rb @@ -0,0 +1,4 @@ +class BusesService < ApplicationRecord + belongs_to :bus + belongs_to :service +end diff --git a/app/models/service.rb b/app/models/service.rb index 9cbb2a32..3d3b64b4 100644 --- a/app/models/service.rb +++ b/app/models/service.rb @@ -9,10 +9,11 @@ class Service < ApplicationRecord 'Телевизор общий', 'Телевизор индивидуальный', 'Стюардесса', - 'Можно не печатать билет', + 'Можно не печатать билет' ].freeze - has_and_belongs_to_many :buses, join_table: :buses_services + has_many :buses_services + has_many :buses, through: :buses_services validates :name, presence: true validates :name, inclusion: { in: SERVICES } diff --git a/app/services/reload_json.rb b/app/services/reload_json.rb new file mode 100644 index 00000000..d3e2e653 --- /dev/null +++ b/app/services/reload_json.rb @@ -0,0 +1,107 @@ +# frozen_string_literal: true + +require 'oj' +class ReloadJson + def initialize(file_name) + @file_name = file_name + @cities = {} + @buses = {} + @buses_services = [] + end + + def call + ActiveRecord::Base.transaction do + clear_tables + create_services + + @connection = ActiveRecord::Base.connection.raw_connection + trips_command = + "copy trips (from_id, to_id, start_time, duration_minutes, price_cents, bus_id) from stdin with csv delimiter ';'" + + @connection.copy_data trips_command do + File.open(file_name) do |ff| + nesting = 0 + str = String.new + + until ff.eof? + ch = ff.read(1) # читаем по одному символу + if ch == '{' # начинается объект, повышается вложенность + nesting += 1 + str << ch + elsif ch == '}' # заканчивается объект, понижается вложенность + nesting -= 1 + str << ch + if nesting.zero? # если закончился объкет уровня trip, парсим и импортируем его + trip = Oj.load(str) + copy_trip(trip) + + str = String.new + end + elsif nesting >= 1 + str << ch + end + end + end + end + + Bus.import buses.values + City.import cities.values + BusesService.import buses_services + end + end + + private + + attr_reader :cities, :buses, :buses_services, :services, :file_name + + def create_services + services = [] + Service::SERVICES.each do |name| + services << Service.new(name: name) + end + Service.import services + @services = Service.all.to_h { |service| [service.name, service.id] } + end + + def clear_tables + City.delete_all + Bus.delete_all + Service.delete_all + Trip.delete_all + BusesService.delete_all + end + + def copy_trip(trip) + from_id = cities.dig(trip['from'], 'id') + to_id = cities.dig(trip['to'], 'id') + service_ids = services.values_at(*trip['bus']['services']) + bus_key = "#{trip['bus']['model']} #{trip['bus']['number']}" + bus_id = buses.dig(bus_key, 'id') + + unless from_id + id = cities.size + 1 + cities[trip['from']] = { 'id' => id, 'name' => trip['from'] } + from_id = id + end + + unless to_id + if cities[trip['from']] == @cities[trip['to']] + to_id = from_id + else + id = cities.size + 1 + @cities[trip['to']] = { 'id' => id, 'name' => trip['to'] } + to_id = id + end + end + + unless bus_id + id = buses.size + 1 + buses[bus_key] = + { 'id' => id, 'number' => trip['bus']['number'], 'model' => trip['bus']['model'] } + service_ids.each { |service_id| buses_services << { 'service_id' => service_id, 'bus_id' => id } } + bus_id = id + end + + @connection.put_copy_data("#{from_id};#{to_id};#{trip['start_time']};#{trip['duration_minutes']};#{trip['price_cents']};#{bus_id}\n") + end +end diff --git a/app/views/trips/_delimiter.html.erb b/app/views/trips/_delimiter.html.erb deleted file mode 100644 index 3f845ad0..00000000 --- a/app/views/trips/_delimiter.html.erb +++ /dev/null @@ -1 +0,0 @@ -==================================================== diff --git a/app/views/trips/_service.html.erb b/app/views/trips/_service.html.erb deleted file mode 100644 index 178ea8c0..00000000 --- a/app/views/trips/_service.html.erb +++ /dev/null @@ -1 +0,0 @@ -
  • <%= "#{service.name}" %>
  • diff --git a/app/views/trips/_services.html.erb b/app/views/trips/_services.html.erb deleted file mode 100644 index 2de639fc..00000000 --- a/app/views/trips/_services.html.erb +++ /dev/null @@ -1,6 +0,0 @@ -
  • Сервисы в автобусе:
  • - diff --git a/app/views/trips/_trip.html.erb b/app/views/trips/_trip.html.erb index fa1de9aa..48846c85 100644 --- a/app/views/trips/_trip.html.erb +++ b/app/views/trips/_trip.html.erb @@ -1,5 +1,16 @@ -
  • <%= "Отправление: #{trip.start_time}" %>
  • -
  • <%= "Прибытие: #{(Time.parse(trip.start_time) + trip.duration_minutes.minutes).strftime('%H:%M')}" %>
  • -
  • <%= "В пути: #{trip.duration_minutes / 60}ч. #{trip.duration_minutes % 60}мин." %>
  • -
  • <%= "Цена: #{trip.price_cents / 100}р. #{trip.price_cents % 100}коп." %>
  • -
  • <%= "Автобус: #{trip.bus.model} №#{trip.bus.number}" %>
  • + +==================================================== diff --git a/app/views/trips/index.html.erb b/app/views/trips/index.html.erb index a60bce41..32597e04 100644 --- a/app/views/trips/index.html.erb +++ b/app/views/trips/index.html.erb @@ -2,15 +2,7 @@ <%= "Автобусы #{@from.name} – #{@to.name}" %>

    - <%= "В расписании #{@trips.count} рейсов" %> + <%= "В расписании #{@trips.size} рейсов" %>

    -<% @trips.each do |trip| %> - - <%= render "delimiter" %> -<% end %> +<%= render partial: 'trip', collection: @trips, as: :trip %> diff --git a/case-study.md b/case-study.md new file mode 100644 index 00000000..45384b40 --- /dev/null +++ b/case-study.md @@ -0,0 +1,28 @@ +# A. Импорт данных +Обработка medium файла занимает ~ 1мин40сек, по памяти - 111MB + +Сразу же приступил к переписанию на потоковую обработку, выделил код в класс в app/services/reload_json.rb, добавил frozen string literal, все инсерты в таблицы заменил на импорты +После оптимизации обработак medium файла - ~ 1 сек, память - 87 MB + +Обработка large.json - ~ 7.6 сек, память - 87MB + +Обработка 1M.json - ~ 68 сек, память - 116MB + +По отчетам профилировки по CPU и памяти не нашел точек для оптимизации +# Б. Отображение расписаний +Начну с rack-mini-profiler + +Без профилировщика страница с 1004 трипов загружается за 3.4 секунды, с профилировщиком - 19 сек + +Профилировщик показал 450 запросов в app/views/trips/index.html.erb, добавил ```includes``` моделей в app/controllers/trips_controller.rb, заменил @trips.count на @trips.size + +Теперь страница загружается за 11.4 сек, кол-во запросов сократилось до 6 + +Судя по логам и профилировщику большинство времени уходит на рендер паршалов, об этом же говорит и rails panel +![Alt text]() +Перенес весь код касаемый одного трипа в паршал, избавился от рендера остальных паршалов, результат +![Alt text]() +Общее время запроса в среднем 315ms + +Считаю на этом можно остановиться, т.к. улучшение запросов почти не принесет пользы, а импорты могут замедлиться из-за добавления индексов + diff --git a/config/database.yml b/config/database.yml index e116cfa6..b4952a4a 100644 --- a/config/database.yml +++ b/config/database.yml @@ -17,6 +17,8 @@ default: &default adapter: postgresql encoding: unicode + username: postgres + password: postgres # For details on connection pooling, see Rails configuration guide # http://guides.rubyonrails.org/configuring.html#database-pooling pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> diff --git a/config/environments/development.rb b/config/environments/development.rb index 1311e3e4..3f2efde1 100644 --- a/config/environments/development.rb +++ b/config/environments/development.rb @@ -1,4 +1,13 @@ Rails.application.configure do + # config.after_initialize do + # Bullet.enable = true + # Bullet.alert = true + # Bullet.bullet_logger = true + # Bullet.console = true + # Bullet.rails_logger = true + # Bullet.add_footer = true + # end + # Settings specified here will take precedence over those in config/application.rb. # In the development environment your application's code is reloaded on @@ -58,4 +67,7 @@ # Use an evented file watcher to asynchronously detect changes in source code, # routes, locales, etc. This feature depends on the listen gem. config.file_watcher = ActiveSupport::EventedFileUpdateChecker + logger = ActiveSupport::Logger.new(STDOUT) + logger.formatter = config.log_formatter + config.logger = ActiveSupport::TaggedLogging.new(logger) end diff --git a/config/environments/test.rb b/config/environments/test.rb index 0a38fd3c..bc5971ab 100644 --- a/config/environments/test.rb +++ b/config/environments/test.rb @@ -1,4 +1,10 @@ Rails.application.configure do + config.after_initialize do + Bullet.enable = true + Bullet.bullet_logger = true + Bullet.raise = true # raise an error if n+1 query occurs + end + # Settings specified here will take precedence over those in config/application.rb. # The test environment is used exclusively to run your application's diff --git a/config/initializers/rack_mini_profiler.rb b/config/initializers/rack_mini_profiler.rb new file mode 100644 index 00000000..ca31423c --- /dev/null +++ b/config/initializers/rack_mini_profiler.rb @@ -0,0 +1,8 @@ +#frozen_string_literal: true + +if Rails.env.development? && ENV['ENABLE_RMP'] + require "rack-mini-profiler" + + # The initializer was required late, so initialize it manually. + Rack::MiniProfilerRails.initialize!(Rails.application) +end diff --git a/config/routes.rb b/config/routes.rb index a2da6a7b..aca1fd7c 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,5 +1,6 @@ Rails.application.routes.draw do # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html - get "/" => "statistics#index" - get "автобусы/:from/:to" => "trips#index" + get '/' => 'statistics#index' + get 'автобусы/:from/:to' => 'trips#index' + mount PgHero::Engine, at: 'pghero' end diff --git a/db/migrate/20231106154303_create_pghero_query_stats.rb b/db/migrate/20231106154303_create_pghero_query_stats.rb new file mode 100644 index 00000000..fbf41263 --- /dev/null +++ b/db/migrate/20231106154303_create_pghero_query_stats.rb @@ -0,0 +1,15 @@ +class CreatePgheroQueryStats < ActiveRecord::Migration[5.2] + def change + create_table :pghero_query_stats do |t| + t.text :database + t.text :user + t.text :query + t.integer :query_hash, limit: 8 + t.float :total_time + t.integer :calls, limit: 8 + t.timestamp :captured_at + end + + add_index :pghero_query_stats, [:database, :captured_at] + end +end diff --git a/db/schema.rb b/db/schema.rb index f6921e45..e7c0bd4c 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -10,7 +10,7 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema.define(version: 2019_03_30_193044) do +ActiveRecord::Schema.define(version: 2023_11_06_154303) do # These are extensions that must be enabled in order to support this database enable_extension "plpgsql" @@ -29,6 +29,17 @@ t.string "name" end + create_table "pghero_query_stats", force: :cascade do |t| + t.text "database" + t.text "user" + t.text "query" + t.bigint "query_hash" + t.float "total_time" + t.bigint "calls" + t.datetime "captured_at" + t.index ["database", "captured_at"], name: "index_pghero_query_stats_on_database_and_captured_at" + end + create_table "services", force: :cascade do |t| t.string "name" end diff --git a/images/Screenshot from 2023-11-06 16-52-17.png b/images/Screenshot from 2023-11-06 16-52-17.png new file mode 100644 index 00000000..62330084 Binary files /dev/null and b/images/Screenshot from 2023-11-06 16-52-17.png differ diff --git a/images/Screenshot from 2023-11-06 18-32-17.png b/images/Screenshot from 2023-11-06 18-32-17.png new file mode 100644 index 00000000..35fcdafa Binary files /dev/null and b/images/Screenshot from 2023-11-06 18-32-17.png differ diff --git a/lib/tasks/utils.rake b/lib/tasks/utils.rake index 540fe871..ef7f6876 100644 --- a/lib/tasks/utils.rake +++ b/lib/tasks/utils.rake @@ -1,34 +1,3 @@ -# Наивная загрузка данных из json-файла в БД -# rake reload_json[fixtures/small.json] task :reload_json, [:file_name] => :environment do |_task, args| - json = JSON.parse(File.read(args.file_name)) - - ActiveRecord::Base.transaction do - City.delete_all - Bus.delete_all - Service.delete_all - Trip.delete_all - ActiveRecord::Base.connection.execute('delete from buses_services;') - - json.each do |trip| - from = City.find_or_create_by(name: trip['from']) - to = City.find_or_create_by(name: trip['to']) - services = [] - trip['bus']['services'].each do |service| - s = Service.find_or_create_by(name: service) - services << s - end - bus = Bus.find_or_create_by(number: trip['bus']['number']) - bus.update(model: trip['bus']['model'], services: services) - - Trip.create!( - from: from, - to: to, - bus: bus, - start_time: trip['start_time'], - duration_minutes: trip['duration_minutes'], - price_cents: trip['price_cents'], - ) - end - end + ReloadJson.new(args.file_name).call end diff --git a/spec/rails_helper.rb b/spec/rails_helper.rb new file mode 100644 index 00000000..b6317b5a --- /dev/null +++ b/spec/rails_helper.rb @@ -0,0 +1,64 @@ +# This file is copied to spec/ when you run 'rails generate rspec:install' +require 'spec_helper' +ENV['RAILS_ENV'] ||= 'test' +require_relative '../config/environment' +# Prevent database truncation if the environment is production +abort("The Rails environment is running in production mode!") if Rails.env.production? +require 'rspec/rails' +# Add additional requires below this line. Rails is not loaded until this point! + +# Requires supporting ruby files with custom matchers and macros, etc, in +# spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are +# run as spec files by default. This means that files in spec/support that end +# in _spec.rb will both be required and run as specs, causing the specs to be +# run twice. It is recommended that you do not name files matching this glob to +# end with _spec.rb. You can configure this pattern with the --pattern +# option on the command line or in ~/.rspec, .rspec or `.rspec-local`. +# +# The following line is provided for convenience purposes. It has the downside +# of increasing the boot-up time by auto-requiring all files in the support +# directory. Alternatively, in the individual `*_spec.rb` files, manually +# require only the support files necessary. +# +# Dir[Rails.root.join('spec', 'support', '**', '*.rb')].sort.each { |f| require f } + +# Checks for pending migrations and applies them before tests are run. +# If you are not using ActiveRecord, you can remove these lines. +begin + ActiveRecord::Migration.maintain_test_schema! +rescue ActiveRecord::PendingMigrationError => e + puts e.to_s.strip + exit 1 +end +RSpec.configure do |config| + # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures + config.fixture_path = "#{::Rails.root}/spec/fixtures" + + # If you're not using ActiveRecord, or you'd prefer not to run each of your + # examples within a transaction, remove the following line or assign false + # instead of true. + config.use_transactional_fixtures = true + + # You can uncomment this line to turn off ActiveRecord support entirely. + # config.use_active_record = false + + # RSpec Rails can automatically mix in different behaviours to your tests + # based on their file location, for example enabling you to call `get` and + # `post` in specs under `spec/controllers`. + # + # You can disable this behaviour by removing the line below, and instead + # explicitly tag your specs with their type, e.g.: + # + # RSpec.describe UsersController, type: :controller do + # # ... + # end + # + # The different available types are documented in the features, such as in + # https://relishapp.com/rspec/rspec-rails/docs + config.infer_spec_type_from_file_location! + + # Filter lines from Rails gems in backtraces. + config.filter_rails_from_backtrace! + # arbitrary gems may also be filtered via: + # config.filter_gems_from_backtrace("gem name") +end diff --git a/spec/services/reload_json_spec.rb b/spec/services/reload_json_spec.rb new file mode 100644 index 00000000..abbd9526 --- /dev/null +++ b/spec/services/reload_json_spec.rb @@ -0,0 +1,12 @@ +# frozen_string_literal: true + +require 'rspec-benchmark' +require 'rails_helper' + +RSpec.configure { |config| config.include RSpec::Benchmark::Matchers } + +describe ReloadJson do + it 'performs under certain time' do + expect { described_class.new('fixtures/medium.json').call }.to perform_under(1000).ms.warmup(1).times + end +end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb new file mode 100644 index 00000000..327b58ea --- /dev/null +++ b/spec/spec_helper.rb @@ -0,0 +1,94 @@ +# This file was generated by the `rails generate rspec:install` command. Conventionally, all +# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. +# The generated `.rspec` file contains `--require spec_helper` which will cause +# this file to always be loaded, without a need to explicitly require it in any +# files. +# +# Given that it is always loaded, you are encouraged to keep this file as +# light-weight as possible. Requiring heavyweight dependencies from this file +# will add to the boot time of your test suite on EVERY test run, even for an +# individual file that may not need all of that loaded. Instead, consider making +# a separate helper file that requires the additional dependencies and performs +# the additional setup, and require it from the spec files that actually need +# it. +# +# See https://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration +RSpec.configure do |config| + # rspec-expectations config goes here. You can use an alternate + # assertion/expectation library such as wrong or the stdlib/minitest + # assertions if you prefer. + config.expect_with :rspec do |expectations| + # This option will default to `true` in RSpec 4. It makes the `description` + # and `failure_message` of custom matchers include text for helper methods + # defined using `chain`, e.g.: + # be_bigger_than(2).and_smaller_than(4).description + # # => "be bigger than 2 and smaller than 4" + # ...rather than: + # # => "be bigger than 2" + expectations.include_chain_clauses_in_custom_matcher_descriptions = true + end + + # rspec-mocks config goes here. You can use an alternate test double + # library (such as bogus or mocha) by changing the `mock_with` option here. + config.mock_with :rspec do |mocks| + # Prevents you from mocking or stubbing a method that does not exist on + # a real object. This is generally recommended, and will default to + # `true` in RSpec 4. + mocks.verify_partial_doubles = true + end + + # This option will default to `:apply_to_host_groups` in RSpec 4 (and will + # have no way to turn it off -- the option exists only for backwards + # compatibility in RSpec 3). It causes shared context metadata to be + # inherited by the metadata hash of host groups and examples, rather than + # triggering implicit auto-inclusion in groups with matching metadata. + config.shared_context_metadata_behavior = :apply_to_host_groups + +# The settings below are suggested to provide a good initial experience +# with RSpec, but feel free to customize to your heart's content. +=begin + # This allows you to limit a spec run to individual examples or groups + # you care about by tagging them with `:focus` metadata. When nothing + # is tagged with `:focus`, all examples get run. RSpec also provides + # aliases for `it`, `describe`, and `context` that include `:focus` + # metadata: `fit`, `fdescribe` and `fcontext`, respectively. + config.filter_run_when_matching :focus + + # Allows RSpec to persist some state between runs in order to support + # the `--only-failures` and `--next-failure` CLI options. We recommend + # you configure your source control system to ignore this file. + config.example_status_persistence_file_path = "spec/examples.txt" + + # Limits the available syntax to the non-monkey patched syntax that is + # recommended. For more details, see: + # https://rspec.info/features/3-12/rspec-core/configuration/zero-monkey-patching-mode/ + config.disable_monkey_patching! + + # Many RSpec users commonly either run the entire suite or an individual + # file, and it's useful to allow more verbose output when running an + # individual spec file. + if config.files_to_run.one? + # Use the documentation formatter for detailed output, + # unless a formatter has already been configured + # (e.g. via a command-line flag). + config.default_formatter = "doc" + end + + # Print the 10 slowest examples and example groups at the + # end of the spec run, to help surface which specs are running + # particularly slow. + config.profile_examples = 10 + + # Run specs in random order to surface order dependencies. If you find an + # order dependency and want to debug it, you can fix the order by providing + # the seed, which is printed after each run. + # --seed 1234 + config.order = :random + + # Seed global randomization in this process using the `--seed` CLI option. + # Setting this allows you to use `--seed` to deterministically reproduce + # test failures related to randomization by passing the same `--seed` value + # as the one that triggered the failure. + Kernel.srand config.seed +=end +end