diff --git a/.gitignore b/.gitignore
index 18b43c9..71f87d2 100644
--- a/.gitignore
+++ b/.gitignore
@@ -7,6 +7,8 @@
# Ignore bundler config.
/.bundle
+/vendor/bundle
+/bundle
# Ignore all logfiles and tempfiles.
/log/*
/tmp/*
diff --git a/.rspec b/.rspec
new file mode 100644
index 0000000..c99d2e7
--- /dev/null
+++ b/.rspec
@@ -0,0 +1 @@
+--require spec_helper
diff --git a/Gemfile b/Gemfile
index 33017fd..45d50bf 100644
--- a/Gemfile
+++ b/Gemfile
@@ -7,10 +7,16 @@ gem 'rails', '~> 5.2.3'
gem 'pg', '>= 0.18', '< 2.0'
gem 'puma', '~> 3.11'
gem 'bootsnap', '>= 1.1.0', require: false
+gem 'activerecord-import'
+gem 'strong_migrations'
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 'rspec-rails', '~> 3.8'
+ gem "rspec-sqlimit"
+ gem 'rails-controller-testing'
+ gem 'capybara'
end
group :development do
@@ -20,6 +26,7 @@ group :development do
end
group :test do
+ gem 'database_cleaner'
end
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
diff --git a/Gemfile.lock b/Gemfile.lock
index eb22e16..ee702f2 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.0.1)
+ activerecord (>= 3.2)
activestorage (5.2.3)
actionpack (= 5.2.3)
activerecord (= 5.2.3)
@@ -42,14 +44,26 @@ GEM
i18n (>= 0.7, < 2)
minitest (~> 5.1)
tzinfo (~> 1.1)
+ addressable (2.6.0)
+ public_suffix (>= 2.0.2, < 4.0)
arel (9.0.0)
bindex (0.6.0)
bootsnap (1.4.2)
msgpack (~> 1.0)
builder (3.2.3)
byebug (11.0.1)
+ capybara (3.16.1)
+ addressable
+ mini_mime (>= 0.1.3)
+ nokogiri (~> 1.8)
+ rack (>= 1.6.0)
+ rack-test (>= 0.6.3)
+ regexp_parser (~> 1.2)
+ xpath (~> 3.2)
concurrent-ruby (1.1.5)
crass (1.0.4)
+ database_cleaner (1.7.0)
+ diff-lcs (1.3)
erubi (1.8.0)
ffi (1.10.0)
globalid (0.4.2)
@@ -77,6 +91,7 @@ GEM
nokogiri (1.10.2)
mini_portile2 (~> 2.4.0)
pg (1.1.4)
+ public_suffix (3.0.3)
puma (3.12.1)
rack (2.0.6)
rack-test (1.1.0)
@@ -94,6 +109,10 @@ GEM
bundler (>= 1.3.0)
railties (= 5.2.3)
sprockets-rails (>= 2.0.0)
+ rails-controller-testing (1.0.4)
+ actionpack (>= 5.0.1.x)
+ actionview (>= 5.0.1.x)
+ activesupport (>= 5.0.1.x)
rails-dom-testing (2.0.3)
activesupport (>= 4.2.0)
nokogiri (>= 1.6)
@@ -109,6 +128,31 @@ GEM
rb-fsevent (0.10.3)
rb-inotify (0.10.0)
ffi (~> 1.0)
+ regexp_parser (1.4.0)
+ rspec (3.8.0)
+ rspec-core (~> 3.8.0)
+ rspec-expectations (~> 3.8.0)
+ rspec-mocks (~> 3.8.0)
+ rspec-core (3.8.0)
+ rspec-support (~> 3.8.0)
+ rspec-expectations (3.8.2)
+ diff-lcs (>= 1.2.0, < 2.0)
+ rspec-support (~> 3.8.0)
+ rspec-mocks (3.8.0)
+ diff-lcs (>= 1.2.0, < 2.0)
+ rspec-support (~> 3.8.0)
+ rspec-rails (3.8.2)
+ actionpack (>= 3.0)
+ activesupport (>= 3.0)
+ railties (>= 3.0)
+ rspec-core (~> 3.8.0)
+ rspec-expectations (~> 3.8.0)
+ rspec-mocks (~> 3.8.0)
+ rspec-support (~> 3.8.0)
+ rspec-sqlimit (0.0.2)
+ rails (> 4.0, < 6.0)
+ rspec (~> 3.0)
+ rspec-support (3.8.0)
ruby_dep (1.5.0)
sprockets (3.7.2)
concurrent-ruby (~> 1.0)
@@ -117,6 +161,8 @@ GEM
actionpack (>= 4.0)
activesupport (>= 4.0)
sprockets (>= 3.0.0)
+ strong_migrations (0.3.1)
+ activerecord (>= 3.2.0)
thor (0.20.3)
thread_safe (0.3.6)
tzinfo (1.2.5)
@@ -129,17 +175,26 @@ GEM
websocket-driver (0.7.0)
websocket-extensions (>= 0.1.0)
websocket-extensions (0.1.3)
+ xpath (3.2.0)
+ nokogiri (~> 1.8)
PLATFORMS
ruby
DEPENDENCIES
+ activerecord-import
bootsnap (>= 1.1.0)
byebug
+ capybara
+ database_cleaner
listen (>= 3.0.5, < 3.2)
pg (>= 0.18, < 2.0)
puma (~> 3.11)
rails (~> 5.2.3)
+ rails-controller-testing
+ rspec-rails (~> 3.8)
+ rspec-sqlimit
+ strong_migrations
tzinfo-data
web-console (>= 3.3.0)
diff --git a/app/controllers/trips_controller.rb b/app/controllers/trips_controller.rb
index acb38be..432551f 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.where(from: @from, to: @to).order(:start_time).eager_load(bus: :services)
end
end
diff --git a/app/models/bus.rb b/app/models/bus.rb
index 1dcc54c..dd73e17 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, source: :service
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 0000000..6219d44
--- /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 9cbb2a3..877bf63 100644
--- a/app/models/service.rb
+++ b/app/models/service.rb
@@ -12,7 +12,8 @@ class Service < ApplicationRecord
'Можно не печатать билет',
].freeze
- has_and_belongs_to_many :buses, join_table: :buses_services
+ has_many :buses_services
+ has_many :buses, through: :buses_services, source: :bus
validates :name, presence: true
validates :name, inclusion: { in: SERVICES }
diff --git a/app/views/trips/_service.html.erb b/app/views/trips/_service.html.erb
index 178ea8c..9ff30fc 100644
--- a/app/views/trips/_service.html.erb
+++ b/app/views/trips/_service.html.erb
@@ -1 +1,3 @@
-
<%= "#{service.name}" %>
+
+
<%= "#{service.name}" %>
+
diff --git a/app/views/trips/_trip.html.erb b/app/views/trips/_trip.html.erb
index fa1de9a..8ee288f 100644
--- a/app/views/trips/_trip.html.erb
+++ b/app/views/trips/_trip.html.erb
@@ -1,5 +1,7 @@
-<%= "Отправление: #{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}" %>
+
+
<%= "Отправление: #{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 a60bce4..5ba9deb 100644
--- a/app/views/trips/index.html.erb
+++ b/app/views/trips/index.html.erb
@@ -2,7 +2,7 @@
<%= "Автобусы #{@from.name} – #{@to.name}" %>
- <%= "В расписании #{@trips.count} рейсов" %>
+ <%= "В расписании #{@trips.length} рейсов" %>
<% @trips.each do |trip| %>
diff --git a/bin/setup b/bin/setup
index f294207..5534a28 100755
--- a/bin/setup
+++ b/bin/setup
@@ -28,8 +28,8 @@ chdir APP_ROOT do
puts "\n== Preparing database =="
system! 'bin/rails db:setup'
- puts "\n== Loading data from fixtures/small.json =="
- system! 'bin/rake reload_json[fixtures/small.json]'
+ puts "\n== Loading data from fixtures/large.json =="
+ system! 'bin/rake reload_json[fixtures/large.json]'
puts "\n== Removing old logs and tempfiles =="
system! 'bin/rails log:clear tmp:clear'
diff --git a/db/migrate/20190403122705_add_indexes_to_trip.rb b/db/migrate/20190403122705_add_indexes_to_trip.rb
new file mode 100644
index 0000000..c50835c
--- /dev/null
+++ b/db/migrate/20190403122705_add_indexes_to_trip.rb
@@ -0,0 +1,10 @@
+class AddIndexesToTrip < ActiveRecord::Migration[5.2]
+ disable_ddl_transaction!
+
+ def change
+ add_index :trips, [:from_id, :to_id], algorithm: :concurrently
+ add_index :trips, :bus_id, algorithm: :concurrently
+ add_index :buses_services, :bus_id, algorithm: :concurrently
+ add_index :buses_services, :service_id, algorithm: :concurrently
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index f6921e4..2e1ff8e 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: 2019_04_03_122705) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
@@ -23,6 +23,8 @@
create_table "buses_services", force: :cascade do |t|
t.integer "bus_id"
t.integer "service_id"
+ t.index ["bus_id"], name: "index_buses_services_on_bus_id"
+ t.index ["service_id"], name: "index_buses_services_on_service_id"
end
create_table "cities", force: :cascade do |t|
@@ -40,6 +42,8 @@
t.integer "duration_minutes"
t.integer "price_cents"
t.integer "bus_id"
+ t.index ["bus_id"], name: "index_trips_on_bus_id"
+ t.index ["from_id", "to_id"], name: "index_trips_on_from_id_and_to_id"
end
end
diff --git a/lib/tasks/utils.rake b/lib/tasks/utils.rake
index 540fe87..b046ad2 100644
--- a/lib/tasks/utils.rake
+++ b/lib/tasks/utils.rake
@@ -10,25 +10,43 @@ task :reload_json, [:file_name] => :environment do |_task, args|
Trip.delete_all
ActiveRecord::Base.connection.execute('delete from buses_services;')
+ cities = {}
+ services = {}
+
+ json.each do |trip|
+ cities[trip['from']] = City.new(name: trip['from']) if trip['from']
+ cities[trip['to']] = City.new(name: trip['to']) if trip['to']
+ trip['bus']['services'].each { |s| services.merge!(s => Service.new(name: s)) }
+ end
+
+ City.import cities.values
+ Service.import services.values
+
+ buses = {}
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,
+ bus = Bus.new(number: trip['bus']['number'], model: trip['bus']['model'])
+ buses.merge!(trip['bus']['number'] => [bus, services.values_at(*trip['bus']['services'])])
+ end
+
+ Bus.import buses.values.map(&:first)
+
+ buses_services = []
+ buses.values.each do |bus_with_service|
+ bus_with_service.second.each { |s| buses_services << { bus_id: bus_with_service.first.id, service_id: s.id } }
+ end
+ BusesService.import buses_services
+
+ trips = json.map! do |trip|
+ {
+ from_id: cities.fetch(trip['from']).id,
+ to_id: cities.fetch(trip['to']).id,
+ bus_id: buses.fetch(trip['bus']['number']).first.id,
start_time: trip['start_time'],
duration_minutes: trip['duration_minutes'],
- price_cents: trip['price_cents'],
- )
+ price_cents: trip['price_cents']
+ }
end
+
+ Trip.import trips
end
end
diff --git a/spec/controllers/trips_controller_spec.rb b/spec/controllers/trips_controller_spec.rb
new file mode 100644
index 0000000..6f4265a
--- /dev/null
+++ b/spec/controllers/trips_controller_spec.rb
@@ -0,0 +1,35 @@
+require 'rails_helper'
+require 'rspec-sqlimit'
+require 'rake'
+require 'benchmark'
+load 'Rakefile'
+
+RSpec.describe TripsController, type: :controller do
+ before do
+ Rake::Task['reload_json'].reenable
+ Rake::Task['reload_json'].invoke('fixtures/small.json')
+ end
+ let!(:trip) { Trip.preload(:from, :to).take }
+
+ it 'correct trips count' do
+ get :index, params: { from: trip.from.name , to: trip.to.name }
+ expect(assigns(:trips).size).to eq(9)
+ expect(assigns(:from).name).to eq(trip.from.name)
+ expect(assigns(:to).name).to eq(trip.to.name)
+ end
+
+
+ it 'run in time' do
+ time = Benchmark.realtime do
+ get :index, params: { from: trip.from.name , to: trip.to.name }
+ end
+
+ puts "Controller time: #{time}"
+
+ expect(time).to be < 0.006
+ end
+
+ it "doesn't send unnecessary requests to db" do
+ expect { get :index, params: { from: trip.from.name , to: trip.to.name } }.not_to exceed_query_limit(2)
+ end
+end
diff --git a/spec/rails_helper.rb b/spec/rails_helper.rb
new file mode 100644
index 0000000..d73d80b
--- /dev/null
+++ b/spec/rails_helper.rb
@@ -0,0 +1,61 @@
+# This file is copied to spec/ when you run 'rails generate rspec:install'
+require 'spec_helper'
+ENV['RAILS_ENV'] ||= 'test'
+require File.expand_path('../../config/environment', __FILE__)
+# 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')].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
+
+ # 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/spec_helper.rb b/spec/spec_helper.rb
new file mode 100644
index 0000000..0317fcc
--- /dev/null
+++ b/spec/spec_helper.rb
@@ -0,0 +1,106 @@
+# 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 http://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
+
+ config.before(:suite) do
+ DatabaseCleaner.strategy = :transaction
+ DatabaseCleaner.clean_with(:truncation)
+ end
+
+ config.around(:each) do |example|
+ DatabaseCleaner.cleaning do
+ example.run
+ end
+ 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:
+ # - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/
+ # - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
+ # - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#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
diff --git a/spec/tasks/reload_json_spec.rb b/spec/tasks/reload_json_spec.rb
new file mode 100644
index 0000000..dbd1984
--- /dev/null
+++ b/spec/tasks/reload_json_spec.rb
@@ -0,0 +1,44 @@
+# frozen_string_literal: true
+
+require 'rails_helper'
+require 'rspec-sqlimit'
+require 'rake'
+require 'benchmark'
+load 'Rakefile'
+
+EXAMPLE_JSON_FILE = 'fixtures/example.json'
+ACTUAL_JSON = 'fixtures/large.json'
+TIMING = {
+ 'fixtures/small.json' => 0.5,
+ 'fixtures/medium.json' => 3.0,
+ 'fixtures/large.json' => 30
+}.freeze
+
+describe 'Rake tasks' do
+ before { Rake::Task['reload_json'].reenable }
+ task = Rake::Task['reload_json']
+
+ it 'correct work' do
+ task.invoke(EXAMPLE_JSON_FILE)
+ expect(City.count).to eq(2)
+ expect(Service.count).to eq(2)
+ expect(Trip.count).to eq(10)
+ expect(Bus.count).to eq(1)
+ expect(BusesService.count).to eq(2)
+ expect(Bus.first.services.size).to eq(2)
+ end
+
+ it 'run in time' do
+ time = Benchmark.realtime do
+ task.invoke(ACTUAL_JSON)
+ end
+
+ puts "Task time: #{time}"
+
+ expect(time).to be < TIMING[ACTUAL_JSON]
+ end
+
+ it "doesn't send unnecessary requests to db" do
+ expect { task.invoke(EXAMPLE_JSON_FILE) }.not_to exceed_query_limit(12)
+ end
+end
diff --git a/spec/views/trips_view_spec.rb b/spec/views/trips_view_spec.rb
new file mode 100644
index 0000000..be37c0f
--- /dev/null
+++ b/spec/views/trips_view_spec.rb
@@ -0,0 +1,37 @@
+require 'rails_helper'
+require 'rspec-sqlimit'
+require 'rake'
+require 'capybara/rails'
+require 'benchmark'
+load 'Rakefile'
+
+describe "trips index view", type: :feature do
+ before do
+ Rake::Task['reload_json'].reenable
+ Rake::Task['reload_json'].invoke('fixtures/large.json')
+ end
+ let!(:trip) { Trip.preload(:from, :to).take }
+
+ it 'correct trips count' do
+ visit URI.parse(URI.escape("/автобусы/#{trip.from.name}/#{trip.to.name}"))
+ expect(page).to have_selector('.trip-item', count: 9)
+ expect(page).to have_selector('.service-item', count: 48)
+ end
+
+
+ # large 2.6, with preload 0.65
+ it 'run in time' do
+ time = Benchmark.realtime do
+ visit URI.parse(URI.escape("/автобусы/#{trip.from.name}/#{trip.to.name}"))
+ end
+
+ puts "Render time: #{time}"
+
+ expect(time).to be < 0.015
+ end
+
+ # small 22, with preload 6
+ it "doesn't send unnecessary requests to db" do
+ expect { visit URI.parse(URI.escape("/автобусы/#{trip.from.name}/#{trip.to.name}")) }.not_to exceed_query_limit(6)
+ end
+end