From 02cad2974f2ac1a30101aa5a3f80e326657832d8 Mon Sep 17 00:00:00 2001 From: Pascal Zumkehr Date: Sat, 29 Mar 2025 15:59:58 +0100 Subject: [PATCH 1/2] Update to rails 8.0 --- .github/workflows/build.yml | 6 +++--- Gemfile | 9 +++++---- Rakefile | 12 ++++++++++-- app/controllers/dry_crud/render_callbacks.rb | 5 ++--- app/views/layouts/application.html.erb | 2 +- app/views/layouts/application.html.haml | 2 +- test/templates/Gemfile.append | 2 -- 7 files changed, 22 insertions(+), 16 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index a7b855a..8b2f667 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -12,7 +12,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - ruby-version: ['3.1', '3.2'] + ruby-version: ['3.3', '3.4'] haml: [true, false] steps: - uses: actions/checkout@v4 @@ -34,7 +34,7 @@ jobs: - name: Set up Ruby uses: ruby/setup-ruby@v1 with: - ruby-version: 3.1 + ruby-version: 3.3 bundler-cache: true # runs 'bundle install' and caches installed gems automatically - name: Run rubocop run: bundle exec rubocop @@ -47,7 +47,7 @@ jobs: - name: Set up Ruby uses: ruby/setup-ruby@v1 with: - ruby-version: 3.1 + ruby-version: 3.3 bundler-cache: true # runs 'bundle install' and caches installed gems automatically - uses: paambaati/codeclimate-action@v5.0.0 env: diff --git a/Gemfile b/Gemfile index f865a8d..1929cbd 100644 --- a/Gemfile +++ b/Gemfile @@ -1,11 +1,11 @@ source 'https://rubygems.org' -gem 'rails', '~> 7.1.0' +gem 'rails', '~> 8.0.0' gem 'puma' gem 'rake' -gem 'sdoc' + gem 'rspec-rails' gem 'haml' @@ -13,7 +13,7 @@ gem 'jbuilder' gem 'kaminari' -gem "sprockets-rails" +gem "propshaft" gem "jsbundling-rails" gem "cssbundling-rails" gem "turbo-rails" @@ -27,11 +27,12 @@ group :development do gem 'web-console' gem 'rubocop' gem 'rubocop-rails' + gem 'sdoc' gem 'spring' end gem 'simplecov', require: false -gem 'debug', platforms: [:mri, :windows] +gem 'debug', platforms: [:mri, :windows], require: "debug/prelude" # platform specific gems diff --git a/Rakefile b/Rakefile index 2b578c0..474a2eb 100644 --- a/Rakefile +++ b/Rakefile @@ -64,13 +64,21 @@ namespace :test do /\A/, "require 'simplecov'\nSimpleCov.start do\n" + " coverage_dir 'coverage/test'\nend\n") + file_replace(File.join(TEST_APP_ROOT, 'test', 'test_helper.rb'), + /module ActiveSupport/, + "Rails.root.glob('test/support/**/*.rb').sort_by(&:to_s).each { |f| require f }\n\n" + + "module ActiveSupport") file_replace(File.join(TEST_APP_ROOT, 'spec', 'spec_helper.rb'), /\A/, "require 'simplecov'\nSimpleCov.start do\n" + " coverage_dir 'coverage/spec'\nend\n") file_replace(File.join(TEST_APP_ROOT, 'spec', 'rails_helper.rb'), - "# Rails.root.glob('spec/support/**/*.rb').sort.each { |f| require f }", - "Rails.root.glob('spec/support/**/*.rb').sort.each { |f| require f }") + "# Rails.root.glob('spec/support/**/*.rb').sort_by(&:to_s).each { |f| require f }", + "Rails.root.glob('spec/support/**/*.rb').sort_by(&:to_s).each { |f| require f }") + + file_replace(File.join(TEST_APP_ROOT, 'spec', 'rails_helper.rb'), + "# config.infer_spec_type_from_file_location!", + "config.infer_spec_type_from_file_location!") end end diff --git a/app/controllers/dry_crud/render_callbacks.rb b/app/controllers/dry_crud/render_callbacks.rb index 3646478..b40bdc4 100644 --- a/app/controllers/dry_crud/render_callbacks.rb +++ b/app/controllers/dry_crud/render_callbacks.rb @@ -17,11 +17,10 @@ module Prepends # If a callback renders or redirects, the action is not rendered. def render(...) options = _normalize_render(...) - callback = "render_#{options[:template]}" - + callback = "render_#{options[:template] || options[:action] || action_name}" run_callbacks(callback) if respond_to?(:"_#{callback}_callbacks", true) - super(...) unless performed? + super unless performed? end private diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb index 5bd95d6..bb485b4 100644 --- a/app/views/layouts/application.html.erb +++ b/app/views/layouts/application.html.erb @@ -10,7 +10,7 @@ <%= csp_meta_tag %> <%= stylesheet_link_tag 'application', 'data-turbo-track': 'reload' %> - <%= javascript_include_tag 'application', 'data-turbo-track': 'reload', defer: true %> + <%= javascript_include_tag 'application', 'data-turbo-track': 'reload', type: 'module', defer: true %> <%= yield :head %> diff --git a/app/views/layouts/application.html.haml b/app/views/layouts/application.html.haml index 64c6acb..a9a85bb 100644 --- a/app/views/layouts/application.html.haml +++ b/app/views/layouts/application.html.haml @@ -12,7 +12,7 @@ = csp_meta_tag = stylesheet_link_tag 'application', 'data-turbo-track': 'reload' - = javascript_include_tag 'application', 'data-turbo-track': 'reload', defer: true + = javascript_include_tag 'application', 'data-turbo-track': 'reload', type: 'module', defer: true = yield :head diff --git a/test/templates/Gemfile.append b/test/templates/Gemfile.append index f98afbf..e98f94a 100644 --- a/test/templates/Gemfile.append +++ b/test/templates/Gemfile.append @@ -2,8 +2,6 @@ gem 'dry_crud', path: '../..' gem 'simplecov', require: false, group: :test -gem 'sqlite3', '~> 1.4', platforms: :ruby - platforms :jruby do gem 'jdbc-sqlite3' gem 'activerecord-jdbcsqlite3-adapter' From d6db4090c46a1c1d871791930924f585a875bf1f Mon Sep 17 00:00:00 2001 From: Pascal Zumkehr Date: Sat, 29 Mar 2025 16:34:13 +0100 Subject: [PATCH 2/2] Format code according to rubocop rails omakase --- .rubocop.yml | 113 +-------- Gemfile | 42 ++-- Rakefile | 142 ++++++----- app/controllers/crud_controller.rb | 12 +- app/controllers/dry_crud/generic_model.rb | 12 +- app/controllers/dry_crud/nestable.rb | 5 +- app/controllers/dry_crud/rememberable.rb | 5 +- app/controllers/dry_crud/render_callbacks.rb | 7 - app/controllers/dry_crud/searchable.rb | 13 +- app/controllers/dry_crud/sortable.rb | 13 +- app/controllers/list_controller.rb | 2 - app/helpers/actions_helper.rb | 18 +- app/helpers/dry_crud/form/builder.rb | 49 ++-- app/helpers/dry_crud/form/control.rb | 18 +- app/helpers/dry_crud/table/actions.rb | 21 +- app/helpers/dry_crud/table/builder.rb | 9 +- app/helpers/dry_crud/table/col.rb | 5 +- app/helpers/dry_crud/table/sorting.rb | 9 +- app/helpers/form_helper.rb | 12 +- app/helpers/format_helper.rb | 22 +- app/helpers/i18n_helper.rb | 18 +- app/helpers/table_helper.rb | 6 +- app/helpers/utility_helper.rb | 20 +- dry_crud.gemspec | 1 + lib/dry_crud.rb | 2 +- lib/dry_crud/engine.rb | 4 +- lib/generators/dry_crud/dry_crud_generator.rb | 34 +-- .../dry_crud/dry_crud_generator_base.rb | 16 +- lib/generators/dry_crud/file_generator.rb | 12 +- .../config/initializers/field_error_proc.rb | 2 +- .../crud_test_models_controller_spec.rb | 238 +++++++++--------- .../helpers/dry_crud/form/builder_spec.rb | 113 ++++----- .../helpers/dry_crud/table/builder_spec.rb | 48 ++-- .../spec/helpers/form_helper_spec.rb | 23 +- .../spec/helpers/format_helper_spec.rb | 180 +++++++------ .../spec/helpers/i18n_helper_spec.rb | 67 +++-- .../spec/helpers/table_helper_spec.rb | 116 +++++---- .../spec/helpers/utility_helper_spec.rb | 39 ++- .../spec/support/crud_controller_examples.rb | 124 ++++----- .../support/crud_controller_test_helper.rb | 18 +- .../crud_test_models_controller_test.rb | 128 +++++----- .../test/helpers/custom_assertions_test.rb | 42 ++-- .../helpers/dry_crud/form/builder_test.rb | 148 +++++------ .../helpers/dry_crud/table/builder_test.rb | 42 ++-- .../test/helpers/form_helper_test.rb | 28 +-- .../test/helpers/format_helper_test.rb | 138 +++++----- .../test/helpers/i18n_helper_test.rb | 54 ++-- .../test/helpers/table_helper_test.rb | 52 ++-- .../test/helpers/utility_helper_test.rb | 32 ++- .../support/crud_controller_test_helper.rb | 28 +-- .../test/support/crud_test_helper.rb | 22 +- .../templates/test/support/crud_test_model.rb | 18 +- .../support/crud_test_models_controller.rb | 28 +-- .../test/support/custom_assertions.rb | 6 +- test/templates/Gemfile.append | 14 +- .../controllers/admin/cities_controller.rb | 4 +- .../controllers/admin/countries_controller.rb | 2 +- .../app/controllers/people_controller.rb | 6 +- .../app/controllers/vips_controller.rb | 8 +- test/templates/app/helpers/people_helper.rb | 4 +- test/templates/app/models/city.rb | 2 +- test/templates/app/models/person.rb | 2 +- .../config/initializers/deprecations.rb | 2 +- test/templates/config/routes.rb | 5 +- test/templates/db/seeds.rb | 74 +++--- test/templates/spec/.rubocop.yml | 57 ----- .../admin/cities_controller_spec.rb | 40 +-- .../admin/countries_controller_spec.rb | 22 +- .../controllers/people_controller_spec.rb | 36 +-- .../spec/routing/cities_routing_spec.rb | 14 +- .../spec/routing/countries_routing_spec.rb | 14 +- test/templates/test/.rubocop.yml | 56 ----- .../admin/cities_controller_test.rb | 38 +-- .../admin/countries_controller_test.rb | 26 +- .../controllers/people_controller_test.rb | 28 +-- 75 files changed, 1242 insertions(+), 1588 deletions(-) delete mode 100644 test/templates/spec/.rubocop.yml delete mode 100644 test/templates/test/.rubocop.yml diff --git a/.rubocop.yml b/.rubocop.yml index 29cdb99..34cac95 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -1,112 +1 @@ -require: - - rubocop-rails - -AllCops: - DisplayCopNames: true - NewCops: enable - Exclude: - # - test/test_app/**/* - - rdoc/**/* - - vendor/**/* - # File generated by Rails - - '**/test_helper.rb' - - '**/spec_helper.rb' - - '**/rails_helper.rb' - - '**/schema.rb' - - '**/seeds.rb' - - '**/initializers/*.rb' - - '**/environments/*.rb' - - '**/config/puma.rb' - - '**/config/routes.rb' - - '**/config/spring.rb' - - '**/db/migrate/*.rb' - - '**/bin/*' - - '**/boot.rb' - - '**/config.ru' - - '**/environment.rb' - - '**/application.rb' - - '**/application_helper.rb' - - '**/application_controller.rb' - - '**/application_job.rb' - - '**/application_system_test_case.rb' - - '**/channels/**/*.rb' - - '**/rails' - - '**/bundle' - - '**/rake' - - '**/Rakefile' - - dry_crud.gemspec - - '**/Gemfile' - - '**/node_modules/**/*' - -Metrics/ClassLength: - Max: 200 - Exclude: - - '**/*_test.rb' - -Metrics/ModuleLength: - Max: 150 - -Metrics/MethodLength: - Max: 18 - -Metrics/CyclomaticComplexity: - Max: 8 - -Metrics/AbcSize: - Max: 20 - Exclude: - - '**/*_test.rb' - -Metrics/BlockLength: - Exclude: - - '**/*_spec.rb' - - '**/*_test.rb' - - '**/*_examples.rb' - -Layout/EmptyLinesAroundClassBody: - Enabled: false - -Layout/EmptyLinesAroundModuleBody: - Enabled: false - -Layout/EmptyLinesAroundBlockBody: - Exclude: - - '**/*_spec.rb' - -Rails/ActionControllerTestCase: - Enabled: false - -Rails/I18nLocaleTexts: - Exclude: - - '**/test/support/*.rb' - -Rails/HelperInstanceVariable: - Enabled: false - -Rails/LexicallyScopedActionFilter: - Enabled: false - -Rails/OutputSafety: - Exclude: - - '**/*_test.rb' - - '**/*_spec.rb' - -Style/ClassVars: - Exclude: - - '**/spec/**/*' - -# Rails does not, we do not -Style/FrozenStringLiteralComment: - Enabled: false - -Style/RegexpLiteral: - Enabled: false - -Style/Attr: - Enabled: false - -Style/IfUnlessModifier: - Enabled: false - -Style/GuardClause: - Enabled: false +inherit_gem: { rubocop-rails-omakase: rubocop.yml } diff --git a/Gemfile b/Gemfile index 1929cbd..b563466 100644 --- a/Gemfile +++ b/Gemfile @@ -1,17 +1,17 @@ -source 'https://rubygems.org' +source "https://rubygems.org" -gem 'rails', '~> 8.0.0' +gem "rails", "~> 8.0.0" -gem 'puma' +gem "puma" -gem 'rake' +gem "rake" -gem 'rspec-rails' +gem "rspec-rails" -gem 'haml' -gem 'jbuilder' +gem "haml" +gem "jbuilder" -gem 'kaminari' +gem "kaminari" gem "propshaft" gem "jsbundling-rails" @@ -19,29 +19,29 @@ gem "cssbundling-rails" gem "turbo-rails" gem "stimulus-rails" -gem 'bootsnap', require: false +gem "bootsnap", require: false -gem 'tzinfo-data', platforms: [:windows, :jruby] +gem "tzinfo-data", platforms: [ :windows, :jruby ] group :development do - gem 'web-console' - gem 'rubocop' - gem 'rubocop-rails' - gem 'sdoc' - gem 'spring' + gem "web-console" + gem "rubocop" + gem "rubocop-rails-omakase" + gem "sdoc" + gem "spring" end -gem 'simplecov', require: false -gem 'debug', platforms: [:mri, :windows], require: "debug/prelude" +gem "simplecov", require: false +gem "debug", platforms: [ :mri, :windows ], require: "debug/prelude" # platform specific gems platforms :ruby do - gem 'sqlite3' + gem "sqlite3" end platforms :jruby do - gem 'jdbc-sqlite3' - gem 'activerecord-jdbcsqlite3-adapter' - gem 'jruby-openssl' + gem "jdbc-sqlite3" + gem "activerecord-jdbcsqlite3-adapter" + gem "jruby-openssl" end diff --git a/Rakefile b/Rakefile index 474a2eb..f05c4ea 100644 --- a/Rakefile +++ b/Rakefile @@ -1,122 +1,120 @@ # encoding: UTF-8 -#!/usr/bin/env rake + +# !/usr/bin/env rake begin - require 'bundler/setup' + require "bundler/setup" rescue LoadError - puts 'You must `gem install bundler` and `bundle install` to run rake tasks' + puts "You must `gem install bundler` and `bundle install` to run rake tasks" end -require 'rake/testtask' -require 'rspec/core/rake_task' -require 'sdoc' -require 'rdoc/task' +require "rake/testtask" +require "rspec/core/rake_task" +require "sdoc" +require "rdoc/task" TEST_APP_ROOT = File.join(File.dirname(__FILE__), - 'test', 'test_app') + "test", "test_app") GENERATOR_ROOT = File.join(File.dirname(__FILE__), - 'lib', 'generators', 'dry_crud') + "lib", "generators", "dry_crud") task default: :test desc "Run all tests" -task test: ['test:unit', 'test:spec'] +task test: [ "test:unit", "test:spec" ] namespace :test do - desc "Run Test::Unit tests" - Rake::TestTask.new(unit: 'test:app:init') do |test| + Rake::TestTask.new(unit: "test:app:init") do |test| test.libs << "test/test_app/test" test.test_files = FileList["test/test_app/test/**/*_test.rb"] test.verbose = true end desc "Run RSpec tests" - RSpec::Core::RakeTask.new(spec: 'test:app:init') do |t| + RSpec::Core::RakeTask.new(spec: "test:app:init") do |t| t.ruby_opts = "-I test/test_app/spec" t.pattern = "test/test_app/spec/**/*_spec.rb" end namespace :app do - desc "Initializes the test application with a couple of classes" - task init: [:seed, :customize] + task init: [ :seed, :customize ] desc "Customize some of the functionality provided by dry_crud" - task customize: ['test:app:add_pagination', - 'test:app:use_bootstrap', - 'test:app:build_assets' - ] + task customize: [ "test:app:add_pagination", + "test:app:use_bootstrap", + "test:app:build_assets" ] desc "Create a rails test application" task :create do unless File.exist?(TEST_APP_ROOT) sh "rails new #{TEST_APP_ROOT} --css=bootstrap --js esbuild" - file_replace(File.join(TEST_APP_ROOT, 'Gemfile'), + file_replace(File.join(TEST_APP_ROOT, "Gemfile"), /\z/, File.read(File.join(File.dirname(__FILE__), - 'test', 'templates', 'Gemfile.append'))) + "test", "templates", "Gemfile.append"))) sh "cd #{TEST_APP_ROOT}; bundle install --local" # update Gemfile.lock sh "cd #{TEST_APP_ROOT}; rails g rspec:install" FileUtils.rm_f(File.join(TEST_APP_ROOT, - 'test', 'performance', 'browsing_test.rb')) - file_replace(File.join(TEST_APP_ROOT, 'test', 'test_helper.rb'), + "test", "performance", "browsing_test.rb")) + file_replace(File.join(TEST_APP_ROOT, "test", "test_helper.rb"), /\A/, - "require 'simplecov'\nSimpleCov.start do\n" + - " coverage_dir 'coverage/test'\nend\n") - file_replace(File.join(TEST_APP_ROOT, 'test', 'test_helper.rb'), + "require \"simplecov\"\nSimpleCov.start do\n" + + " coverage_dir \"coverage/test\"\nend\n") + file_replace(File.join(TEST_APP_ROOT, "test", "test_helper.rb"), /module ActiveSupport/, - "Rails.root.glob('test/support/**/*.rb').sort_by(&:to_s).each { |f| require f }\n\n" + + "Rails.root.glob(\"test/support/**/*.rb\").sort_by(&:to_s).each { |f| require f }\n\n" + "module ActiveSupport") - file_replace(File.join(TEST_APP_ROOT, 'spec', 'spec_helper.rb'), + file_replace(File.join(TEST_APP_ROOT, "spec", "spec_helper.rb"), /\A/, - "require 'simplecov'\nSimpleCov.start do\n" + - " coverage_dir 'coverage/spec'\nend\n") - file_replace(File.join(TEST_APP_ROOT, 'spec', 'rails_helper.rb'), + "require \"simplecov\"\nSimpleCov.start do\n" + + " coverage_dir \"coverage/spec\"\nend\n") + file_replace(File.join(TEST_APP_ROOT, "spec", "rails_helper.rb"), "# Rails.root.glob('spec/support/**/*.rb').sort_by(&:to_s).each { |f| require f }", - "Rails.root.glob('spec/support/**/*.rb').sort_by(&:to_s).each { |f| require f }") + "Rails.root.glob(\"spec/support/**/*.rb\").sort_by(&:to_s).each { |f| require f }") - file_replace(File.join(TEST_APP_ROOT, 'spec', 'rails_helper.rb'), + file_replace(File.join(TEST_APP_ROOT, "spec", "rails_helper.rb"), "# config.infer_spec_type_from_file_location!", "config.infer_spec_type_from_file_location!") end end desc "Run the dry_crud generator for the test application" - task generate_crud: [:create, :environment] do - require File.join(GENERATOR_ROOT, 'dry_crud_generator_base') - require File.join(GENERATOR_ROOT, 'dry_crud_generator') + task generate_crud: [ :create, :environment ] do + require File.join(GENERATOR_ROOT, "dry_crud_generator_base") + require File.join(GENERATOR_ROOT, "dry_crud_generator") DryCrudGenerator.new([], { force: true, - templates: %w[1 yes true].include?(ENV['HAML']) ? 'haml' : 'erb', - tests: 'all' }, + templates: %w[1 yes true].include?(ENV["HAML"]) ? "haml" : "erb", + tests: "all" }, destination_root: TEST_APP_ROOT).invoke_all end task :environment do - ENV['RAILS_ROOT'] = TEST_APP_ROOT - ENV['RAILS_ENV'] = 'test' + ENV["RAILS_ROOT"] = TEST_APP_ROOT + ENV["RAILS_ENV"] = "test" - require(File.join(TEST_APP_ROOT, 'config', 'environment')) + require(File.join(TEST_APP_ROOT, "config", "environment")) end desc "Populates the test application with some models and controllers" - task populate: [:generate_crud] do + task populate: [ :generate_crud ] do # copy test app templates FileUtils.cp_r(File.join(File.dirname(__FILE__), - 'test', 'templates', '.'), + "test", "templates", "."), TEST_APP_ROOT) # copy shared fixtures FileUtils.cp_r(File.join(File.dirname(__FILE__), - 'test', 'templates', 'test', 'fixtures'), - File.join(TEST_APP_ROOT, 'spec')) + "test", "templates", "test", "fixtures"), + File.join(TEST_APP_ROOT, "spec")) # remove unused template type, erb or haml - exclude = %w[1 yes true].include?(ENV['HAML']) ? 'erb' : 'haml' + exclude = %w[1 yes true].include?(ENV["HAML"]) ? "erb" : "haml" Dir.glob(File.join(TEST_APP_ROOT, - 'app', 'views', '**', "*.#{exclude}")).each do |f| + "app", "views", "**", "*.#{exclude}")).each do |f| FileUtils.rm(f) end end @@ -134,26 +132,26 @@ namespace :test do desc "Adds pagination to the test app" task :add_pagination do list_ctrl = File.join(TEST_APP_ROOT, - 'app', 'controllers', 'list_controller.rb') + "app", "controllers", "list_controller.rb") file_replace(list_ctrl, /def list_entries\n\s+(.+)\s*\n/, "def list_entries\n" + " list = \\1\n" + " list.page(params[:page]).per(10)\n") file_replace(File.join(TEST_APP_ROOT, - 'app', 'views', 'list', 'index.html.erb'), - "<%= render 'list' %>", - "<%= paginate entries %>\n\n<%= render 'list' %>") + "app", "views", "list", "index.html.erb"), + "<%= render \"list\" %>", + "<%= paginate entries %>\n\n<%= render \"list\" %>") file_replace(File.join(TEST_APP_ROOT, - 'app', 'views', 'list', 'index.html.haml'), - "= render 'list'", - "= paginate entries\n\n= render 'list'") + "app", "views", "list", "index.html.haml"), + "= render \"list\"", + "= paginate entries\n\n= render \"list\"") end desc "Remove sample scss in the test app" task :use_bootstrap do FileUtils.rm_f(File.join(TEST_APP_ROOT, - 'app', 'assets', 'stylesheets', 'sample.scss')) + "app", "assets", "stylesheets", "sample.scss")) end desc "Build javascript and css in the test app" @@ -166,35 +164,35 @@ end desc "Clean up all generated resources" task :clobber do FileUtils.rm_rf(TEST_APP_ROOT) - FileUtils.rm_rf('pkg') + FileUtils.rm_rf("pkg") end Bundler::GemHelper.install_tasks # :rdoc task Rake::RDocTask.new do |rdoc| - rdoc.title = 'dry_crud' - rdoc.options << '--all' << '--line-numbers' << '--fmt' << 'sdoc' + rdoc.title = "dry_crud" + rdoc.options << "--all" << "--line-numbers" << "--fmt" << "sdoc" rdoc.rdoc_files.include( - *FileList.new('*') do |list| + *FileList.new("*") do |list| list.exclude(/(^|[^.a-z])[a-z]+/) - list.exclude('TODO') + list.exclude("TODO") end.to_a) - rdoc.rdoc_files.include('app/**/*.rb') - rdoc.rdoc_files.include('lib/generators/dry_crud/templates/**/*.rb') - rdoc.rdoc_files.exclude('lib/generators/dry_crud/templates/**/*_test.rb') - rdoc.rdoc_files.exclude('lib/generators/dry_crud/templates/**/*_spec.rb') - rdoc.rdoc_files.exclude('lib/generators/dry_crud/templates/**/*_examples.rb') - rdoc.rdoc_files.exclude('TODO') - - rdoc.rdoc_dir = 'rdoc' - rdoc.main = 'README.rdoc' + rdoc.rdoc_files.include("app/**/*.rb") + rdoc.rdoc_files.include("lib/generators/dry_crud/templates/**/*.rb") + rdoc.rdoc_files.exclude("lib/generators/dry_crud/templates/**/*_test.rb") + rdoc.rdoc_files.exclude("lib/generators/dry_crud/templates/**/*_spec.rb") + rdoc.rdoc_files.exclude("lib/generators/dry_crud/templates/**/*_examples.rb") + rdoc.rdoc_files.exclude("TODO") + + rdoc.rdoc_dir = "rdoc" + rdoc.main = "README.rdoc" end desc "Deploy rdoc to website" task site: :rdoc do - if ENV['DEST'] - sh "rsync -rzv rdoc/ #{ENV['DEST']}" + if ENV["DEST"] + sh "rsync -rzv rdoc/ #{ENV["DEST"]}" else puts "Please specify a destination with DEST=user@server:/deploy/dir" end @@ -208,5 +206,5 @@ def file_replace(file, expression, replacement) if text == replaced puts "WARN: Nothing replaced in '#{file}' for '#{expression}'" end - File.open(file, 'w') { |f| f.puts replaced } + File.open(file, "w") { |f| f.puts replaced } end diff --git a/app/controllers/crud_controller.rb b/app/controllers/crud_controller.rb index 8138dfb..f48593b 100644 --- a/app/controllers/crud_controller.rb +++ b/app/controllers/crud_controller.rb @@ -8,7 +8,6 @@ # With the help of additional callbacks, it is possible to hook into the # action procedures without overriding the entire method. class CrudController < ListController - class_attribute :permitted_attrs # Defines before and after callback hooks for create, update, save and @@ -139,7 +138,7 @@ def assign_attributes # The form params for this model. def model_params - params.require(model_identifier).permit(permitted_attrs) + params.expect(model_identifier => permitted_attrs) end # Path of the index page to return to. @@ -186,7 +185,7 @@ def redirect_on_success(**options) # Perform a redirect after a failed operation and set a flash alert. def redirect_on_failure(**options) location = options[:location] || - request.env['HTTP_REFERER'].presence || + request.env["HTTP_REFERER"].presence || index_path flash[:alert] ||= error_messages.presence || flash_message(:failure) redirect_to location @@ -211,10 +210,10 @@ def render_failure_json # or crud.{action_name}.flash.{state} as fallback. def flash_message(state) scope = "#{action_name}.flash.#{state}" - keys = [:"#{controller_name}.#{scope}_html", + keys = [ :"#{controller_name}.#{scope}_html", :"#{controller_name}.#{scope}", :"crud.#{scope}_html", - :"crud.#{scope}"] + :"crud.#{scope}" ] I18n.t(keys.shift, model: full_entry_label, default: keys) end @@ -229,7 +228,7 @@ def full_entry_label def error_messages # rubocop:disable Rails/OutputSafety escaped = entry.errors.full_messages.map { |m| ERB::Util.html_escape(m) } - escaped.join('
').html_safe + escaped.join("
").html_safe # rubocop:enable Rails/OutputSafety end @@ -242,5 +241,4 @@ def before_render_form(*methods) before_render_edit(*methods) end end - end diff --git a/app/controllers/dry_crud/generic_model.rb b/app/controllers/dry_crud/generic_model.rb index f415720..aa96ece 100644 --- a/app/controllers/dry_crud/generic_model.rb +++ b/app/controllers/dry_crud/generic_model.rb @@ -1,5 +1,4 @@ module DryCrud - # Connects the including controller to the model whose name corrsponds to # the controller's name. # @@ -7,13 +6,12 @@ module DryCrud # Additional helper methods store and retrieve values in instance variables # named after their class. module GenericModel - extend ActiveSupport::Concern included do helper_method :model_class, :models_label, :path_args - delegate :model_class, :models_label, :model_identifier, to: 'self.class' + delegate :model_class, :models_label, :model_identifier, to: "self.class" end # The scope where model entries will be listed and created. @@ -43,11 +41,11 @@ def model_ivar_get(plural: false) def model_ivar_set(value) name = if value.respond_to?(:klass) # ActiveRecord::Relation ivar_name(value.klass).pluralize - elsif value.respond_to?(:each) # Array + elsif value.respond_to?(:each) # Array ivar_name(value.first.class).pluralize - else + else ivar_name(value.class) - end + end instance_variable_set(:"@#{name}", value) end @@ -57,7 +55,6 @@ def ivar_name(klass) # Class methods from GenericModel. module ClassMethods - # The ActiveRecord class of the model. def model_class @model_class ||= controller_name.classify.constantize @@ -77,7 +74,6 @@ def models_label(plural: true) model_class.model_name.human(opts) end - end end end diff --git a/app/controllers/dry_crud/nestable.rb b/app/controllers/dry_crud/nestable.rb index 97d4e12..3c62563 100644 --- a/app/controllers/dry_crud/nestable.rb +++ b/app/controllers/dry_crud/nestable.rb @@ -1,5 +1,4 @@ module DryCrud - # Provides functionality to nest controllers/resources. # If a controller is nested, the parent classes and namespaces # may be defined as an array in the +nesting+ class attribute. @@ -8,7 +7,6 @@ module DryCrud # namespace, may define this attribute as follows: # self.nesting = :admin, Country module Nestable - # Adds the :nesting class attribute and parent helper methods # to the including controller. def self.prepended(klass) @@ -45,7 +43,7 @@ def parent_entry(clazz) # An array of objects used in url_for and related functions. def path_args(last) - parents + [last] + parents + [ last ] end # Uses the parent entry (if any) to constrain the model scope. @@ -61,6 +59,5 @@ def model_scope def parent_scope parent.send(model_class.name.underscore.pluralize) end - end end diff --git a/app/controllers/dry_crud/rememberable.rb b/app/controllers/dry_crud/rememberable.rb index 7b12e91..46b90d7 100644 --- a/app/controllers/dry_crud/rememberable.rb +++ b/app/controllers/dry_crud/rememberable.rb @@ -1,5 +1,4 @@ module DryCrud - # Remembers certain params of the index action in order to return # to the same list after an entry was viewed or edited. # If the index is called with a param :returning, the remembered params @@ -11,14 +10,13 @@ module DryCrud # The params are stored separately for each different +remember_key+, which # defaults to the current request's path. module Rememberable - extend ActiveSupport::Concern included do class_attribute :remember_params self.remember_params = %w[q sort sort_dir page] - before_action :handle_remember_params, only: [:index] + before_action :handle_remember_params, only: [ :index ] end private @@ -61,6 +59,5 @@ def remembered_params def remember_key request.path end - end end diff --git a/app/controllers/dry_crud/render_callbacks.rb b/app/controllers/dry_crud/render_callbacks.rb index b40bdc4..e5aa3cd 100644 --- a/app/controllers/dry_crud/render_callbacks.rb +++ b/app/controllers/dry_crud/render_callbacks.rb @@ -1,8 +1,6 @@ module DryCrud - # Provide +before_render+ callbacks. module RenderCallbacks - extend ActiveSupport::Concern included do @@ -12,7 +10,6 @@ module RenderCallbacks # Prepended methods for callbacks. module Prepends - # Helper method to run +before_render+ callbacks and render the action. # If a callback renders or redirects, the action is not rendered. def render(...) @@ -32,12 +29,10 @@ def with_callbacks(*kinds, &block) -> { run_callbacks(e, &a) } end.call end - end # Class methods for callbacks. module ClassMethods - # Defines before callbacks for the render actions. def define_render_callbacks(*actions) args = actions.map { |a| :"render_#{a}" } @@ -57,8 +52,6 @@ def render_callback_terminator terminate end end - end - end end diff --git a/app/controllers/dry_crud/searchable.rb b/app/controllers/dry_crud/searchable.rb index 18aeef2..52d9e0a 100644 --- a/app/controllers/dry_crud/searchable.rb +++ b/app/controllers/dry_crud/searchable.rb @@ -1,10 +1,8 @@ module DryCrud - # The search functionality for the index table. # Define an array of searchable string columns in your subclassing # controllers using the class attribute +search_columns+. module Searchable - extend ActiveSupport::Concern included do @@ -18,7 +16,6 @@ module Searchable # Prepended methods for searching. module Prepends - private # Enhance the list entries with an optional search criteria @@ -61,24 +58,20 @@ def search_column_condition(word) def search_support? search_columns.present? end - end # Class methods for Searchable. module ClassMethods - # All search columns divided in table and field names. def search_tables_and_fields @search_tables_and_fields ||= search_columns.map do |f| - if f.to_s.include?('.') - f.split('.', 2) + if f.to_s.include?(".") + f.split(".", 2) else - [model_class.table_name, f] + [ model_class.table_name, f ] end end end - end - end end diff --git a/app/controllers/dry_crud/sortable.rb b/app/controllers/dry_crud/sortable.rb index e528425..9a80cfe 100644 --- a/app/controllers/dry_crud/sortable.rb +++ b/app/controllers/dry_crud/sortable.rb @@ -1,10 +1,8 @@ module DryCrud - # Sort functionality for the index table. # Define a default sort expression that is always appended to the # current sort params with the class attribute +default_sort+. module Sortable - extend ActiveSupport::Concern included do @@ -20,7 +18,6 @@ module Sortable # Class methods for sorting. module ClassMethods - # Define a map of (virtual) attributes to SQL order expressions. # May be used for sorting table columns that do not appear directly # in the database table. E.g., map city_id: 'cities.name' to @@ -29,20 +26,18 @@ def sort_mappings=(hash) self.sort_mappings_with_indifferent_access = hash.with_indifferent_access end - end # Prepended methods for sorting. module Prepends - private # Enhance the list entries with an optional sort order. def list_entries sortable = sortable?(params[:sort]) if sortable || default_sort - clause = [sortable ? sort_expression : nil, default_sort] - super.reorder(Arel.sql(clause.compact.join(', '))) + clause = [ sortable ? sort_expression : nil, default_sort ] + super.reorder(Arel.sql(clause.compact.join(", "))) else super end @@ -57,7 +52,7 @@ def sort_expression # The sort direction, either 'asc' or 'desc'. def sort_dir - params[:sort_dir] == 'desc' ? 'DESC' : 'ASC' + params[:sort_dir] == "desc" ? "DESC" : "ASC" end # Returns true if the passed attribute is sortable. @@ -66,8 +61,6 @@ def sortable?(attr) model_class.column_names.include?(attr.to_s) || sort_mappings_with_indifferent_access.include?(attr)) end - end - end end diff --git a/app/controllers/list_controller.rb b/app/controllers/list_controller.rb index 91d0ec6..efcdcfc 100644 --- a/app/controllers/list_controller.rb +++ b/app/controllers/list_controller.rb @@ -7,7 +7,6 @@ # Furthermore, it remembers the last search and sort parameters after the # user returns from a displayed or edited entry. class ListController < ApplicationController - include DryCrud::GenericModel prepend DryCrud::Nestable include DryCrud::RenderCallbacks @@ -48,5 +47,4 @@ def list_entries # Include these modules after the #list_entries method is defined. include DryCrud::Searchable include DryCrud::Sortable - end diff --git a/app/helpers/actions_helper.rb b/app/helpers/actions_helper.rb index d0e4c8e..fefcdd7 100644 --- a/app/helpers/actions_helper.rb +++ b/app/helpers/actions_helper.rb @@ -3,19 +3,18 @@ # of action links, change the method #action_link, e.g. to generate a button. # The common crud actions show, edit, destroy, index and add are provided here. module ActionsHelper - # A generic helper method to create action links. # These link could be styled to look like buttons, for example. def action_link(label, icon = nil, url = {}, html_options = {}) - add_css_class html_options, 'action btn btn-light' + add_css_class html_options, "action btn btn-light" link_to(icon ? action_icon(icon, label) : label, url, html_options) end # Outputs an icon for an action with an optional label. def action_icon(icon, label = nil) - html = tag.i('', class: "bi-#{icon}") - html << ' ' << label if label + html = tag.i("", class: "bi-#{icon}") + html << " " << label if label html end @@ -23,7 +22,7 @@ def action_icon(icon, label = nil) # Uses the current +entry+ if no path is given. def show_action_link(path = nil) path ||= path_args(entry) - action_link(ti('link.show'), 'zoom-in', path) + action_link(ti("link.show"), "zoom-in", path) end # Standard edit action to given path. @@ -31,14 +30,14 @@ def show_action_link(path = nil) def edit_action_link(path = nil) path ||= path_args(entry) path = edit_polymorphic_path(path) unless path.is_a?(String) - action_link(ti('link.edit'), 'pencil', path) + action_link(ti("link.edit"), "pencil", path) end # Standard destroy action to the given path. # Uses the current +entry+ if no path is given. def destroy_action_link(path = nil) path ||= path_args(entry) - action_link(ti('link.delete'), 'trash', path, + action_link(ti("link.delete"), "trash", path, data: { 'turbo-confirm': ti(:confirm_delete), 'turbo-method': :delete }) end @@ -48,7 +47,7 @@ def destroy_action_link(path = nil) def index_action_link(path = nil, url_options = { returning: true }) path ||= path_args(model_class) path = polymorphic_path(path, url_options) unless path.is_a?(String) - action_link(ti('link.list'), 'list', path) + action_link(ti("link.list"), "list", path) end # Standard add action to given path. @@ -56,7 +55,6 @@ def index_action_link(path = nil, url_options = { returning: true }) def add_action_link(path = nil, url_options = {}) path ||= path_args(model_class) path = new_polymorphic_path(path, url_options) unless path.is_a?(String) - action_link(ti('link.add'), 'plus', path) + action_link(ti("link.add"), "plus", path) end - end diff --git a/app/helpers/dry_crud/form/builder.rb b/app/helpers/dry_crud/form/builder.rb index eeb9a2d..79f6426 100644 --- a/app/helpers/dry_crud/form/builder.rb +++ b/app/helpers/dry_crud/form/builder.rb @@ -1,6 +1,5 @@ module DryCrud module Form - # A form builder that automatically selects the corresponding input field # for ActiveRecord column types. Convenience methods for each column type # allow one to customize the different fields. @@ -14,7 +13,6 @@ module Form # See the Control class for how to customize the html rendered for a # single input field. class Builder < ActionView::Helpers::FormBuilder - class_attribute :control_class self.control_class = Control @@ -70,10 +68,10 @@ def string_field(attr, **html_options) # Render a boolean field. def boolean_field(attr, **html_options) - tag.div(class: 'checkbox') do + tag.div(class: "checkbox") do tag.label do - detail = html_options.delete(:detail) || ' '.html_safe - safe_join([check_box(attr, html_options), ' ', detail]) + detail = html_options.delete(:detail) || " ".html_safe + safe_join([ check_box(attr, html_options), " ", detail ]) end end end @@ -82,7 +80,7 @@ def boolean_field(attr, **html_options) %w[text_field password_field email_field number_field date_field time_field datetime_field].each do |method| define_method(method) do |attr, **html_options| - add_css_class(html_options, 'form-control') + add_css_class(html_options, "form-control") super(attr, html_options) end end @@ -93,7 +91,7 @@ def integer_field(attr, **html_options) end def float_field(attr, **html_options) - html_options[:step] ||= 'any' + html_options[:step] ||= "any" number_field(attr, **html_options) end @@ -105,9 +103,9 @@ def decimal_field(attr, **html_options) # Customize the standard text area to have 5 rows by default. def text_area(attr, **html_options) - add_css_class(html_options, 'form-control') + add_css_class(html_options, "form-control") html_options[:rows] ||= 5 - super(attr, **html_options) + super end # Render a select element for a :belongs_to association defined by attr. @@ -118,7 +116,7 @@ def text_area(attr, **html_options) def belongs_to_field(attr, **html_options) list = association_entries(attr, **html_options).to_a if list.present? - add_css_class(html_options, 'form-control') + add_css_class(html_options, "form-control") collection_select(attr, list, :id, :to_s, select_options(attr, **html_options), **html_options) @@ -140,7 +138,7 @@ def belongs_to_field(attr, **html_options) # association. def has_many_field(attr, **html_options) html_options[:multiple] = true - add_css_class(html_options, 'multiselect') + add_css_class(html_options, "multiselect") belongs_to_field(attr, **html_options) end # rubocop:enable Naming/PredicateName @@ -149,46 +147,46 @@ def has_many_field(attr, **html_options) # Render the error messages for the current form. def error_messages - @template.render('shared/error_messages', + @template.render("shared/error_messages", errors: @object.errors, object: @object) end # Renders the given content with an addon. def with_addon(content, addon) - tag.div(class: 'input-group') do - content + tag.span(addon, class: 'input-group-text') + tag.div(class: "input-group") do + content + tag.span(addon, class: "input-group-text") end end # Renders a static text where otherwise form inputs appear. def static_text(text) - tag.p(text, class: 'form-control-static') + tag.p(text, class: "form-control-static") end # Generates a help block for fields def help_block(text) - tag.p(text, class: 'help-block') + tag.p(text, class: "help-block") end # Render a submit button and a cancel link for this form. - def standard_actions(submit_label = ti('button.save'), cancel_url = nil) - tag.div(class: 'col-md-offset-2 col-md-8') do - safe_join([submit_button(submit_label), - cancel_link(cancel_url)], - ' ') + def standard_actions(submit_label = ti("button.save"), cancel_url = nil) + tag.div(class: "col-md-offset-2 col-md-8") do + safe_join([ submit_button(submit_label), + cancel_link(cancel_url) ], + " ") end end # Render a standard submit button with the given label. - def submit_button(label = ti('button.save')) - button(label, class: 'btn btn-primary', data: { disable_with: label }) + def submit_button(label = ti("button.save")) + button(label, class: "btn btn-primary", data: { disable_with: label }) end # Render a cancel link pointing to the given url. def cancel_link(url = nil) url ||= cancel_url - link_to(ti('button.cancel'), url, class: 'cancel') + link_to(ti("button.cancel"), url, class: "cancel") end # Depending if the given attribute must be present, return @@ -265,7 +263,7 @@ def respond_to_missing?(name, include_private = false) # Checks if the passed name corresponds to a field method with a # 'labeled_' prefix. def labeled_field_method?(name) - prefix = 'labeled_' + prefix = "labeled_" if name.to_s.start_with?(prefix) field_method = name.to_s[prefix.size..] field_method if respond_to?(field_method) @@ -321,7 +319,6 @@ def cancel_url options[:cancel_url_edit] || options[:cancel_url] end end - end end end diff --git a/app/helpers/dry_crud/form/control.rb b/app/helpers/dry_crud/form/control.rb index 14eac3e..389d49e 100644 --- a/app/helpers/dry_crud/form/control.rb +++ b/app/helpers/dry_crud/form/control.rb @@ -1,18 +1,16 @@ module DryCrud module Form - # Internal class to handle the rendering of a single form control, # consisting of a label, input field, addon, help text or # required mark. class Control - attr_reader :builder, :attr, :args, :options, :addon, :help delegate :tag, :object, :add_css_class, to: :builder # Html displayed to mark an input as required. - REQUIRED_MARK = '*'.freeze + REQUIRED_MARK = "*".freeze # Number of default input field span columns depending # on the #field_method. @@ -70,8 +68,8 @@ def render_labeled(content = nil) # Create the HTML markup for any labeled content. def labeled - tag.div(class: 'row mb-3') do - builder.label(attr, caption, class: 'col-md-2 col-form-label') + + tag.div(class: "row mb-3") do + builder.label(attr, caption, class: "col-md-2 col-form-label") + tag.div(content, class: "col-md-#{span}") end end @@ -98,8 +96,8 @@ def content # depending on the attribute. def input @input ||= begin - options[:required] = 'required' if required - add_css_class(options, 'is-invalid') if errors? + options[:required] = "required" if required + add_css_class(options, "is-invalid") if errors? builder.send(field_method, attr, *args, **options) end end @@ -143,9 +141,9 @@ def detect_field_method :belongs_to_field elsif association_kind?(:has_and_belongs_to_many, :has_many) :has_many_field - elsif attr.to_s.include?('password') + elsif attr.to_s.include?("password") :password_field - elsif attr.to_s.include?('email') + elsif attr.to_s.include?("email") :email_field elsif builder.respond_to?(:"#{type}_field") :"#{type}_field" @@ -170,8 +168,6 @@ def association_kind?(*macros) false end end - end - end end diff --git a/app/helpers/dry_crud/table/actions.rb b/app/helpers/dry_crud/table/actions.rb index a812c88..8ed7e34 100644 --- a/app/helpers/dry_crud/table/actions.rb +++ b/app/helpers/dry_crud/table/actions.rb @@ -1,12 +1,10 @@ module DryCrud module Table - # Adds action columns to the table builder. # Predefined actions are available for show, edit and destroy. # Additionally, a special col type to define cells linked to the show page # of the row entry is provided. module Actions - extend ActiveSupport::Concern included do @@ -30,7 +28,7 @@ def show_action_col(**html_options, &block) action_col do |entry| path = action_path(entry, &block) if path - table_action_link('zoom-in', + table_action_link("zoom-in", path, **html_options.clone) end @@ -45,7 +43,7 @@ def edit_action_col(**html_options, &block) path = action_path(entry, &block) if path path = edit_polymorphic_path(path) unless path.is_a?(String) - table_action_link('pencil', path, **html_options.clone) + table_action_link("pencil", path, **html_options.clone) end end end @@ -57,12 +55,11 @@ def destroy_action_col(**html_options, &block) action_col do |entry| path = action_path(entry, &block) if path - table_action_link('trash', + table_action_link("trash", path, - **html_options.merge( - data: { 'turbo-confirm': ti(:confirm_delete), - 'turbo-method': :delete } - )) + **html_options, + data: { 'turbo-confirm': ti(:confirm_delete), + 'turbo-method': :delete }) end end end @@ -70,13 +67,13 @@ def destroy_action_col(**html_options, &block) # Action column inside a table. No header. # The cell content should be defined in the passed block. def action_col(&block) - col('', class: 'action', &block) + col("", class: "action", &block) end # Generic action link inside a table. def table_action_link(icon, url, **html_options) add_css_class(html_options, "bi-#{icon}") - link_to('', url, html_options) + link_to("", url, html_options) end private @@ -86,8 +83,6 @@ def table_action_link(icon, url, **html_options) def action_path(entry) block_given? ? yield(entry) : path_args(entry) end - end - end end diff --git a/app/helpers/dry_crud/table/builder.rb b/app/helpers/dry_crud/table/builder.rb index eda1643..cb5ec12 100644 --- a/app/helpers/dry_crud/table/builder.rb +++ b/app/helpers/dry_crud/table/builder.rb @@ -1,6 +1,5 @@ module DryCrud module Table - # A simple helper to easily define tables listing several rows of the same # data type. # @@ -10,7 +9,6 @@ module Table # t.attrs :name, :city # end class Builder - include Sorting include Actions @@ -39,7 +37,7 @@ def self.table(entries, template, **options) # Define a column for the table with the given header, the html_options # used for each td and a block rendering the contents of a cell for the # current entry. The columns appear in the order they are defined. - def col(header = '', **html_options, &block) + def col(header = "", **html_options, &block) @cols << Col.new(header, html_options, @template, block) end @@ -76,9 +74,9 @@ def align_class(attr) entry = entries.present? ? entry_class.new : nil case column_type(entry, attr) when :integer, :float, :decimal - 'right' unless association(entry, attr, :belongs_to) + "right" unless association(entry, attr, :belongs_to) when :boolean - 'center' + "center" end end @@ -110,7 +108,6 @@ def entry_class entries.first.class end end - end end end diff --git a/app/helpers/dry_crud/table/col.rb b/app/helpers/dry_crud/table/col.rb index ddf21d5..d6e1214 100644 --- a/app/helpers/dry_crud/table/col.rb +++ b/app/helpers/dry_crud/table/col.rb @@ -1,9 +1,7 @@ module DryCrud module Table - # Helper class to store column information. class Col # :nodoc: - delegate :tag, :capture, to: :template attr_reader :header, :html_options, :template, :block @@ -17,7 +15,7 @@ def initialize(header, html_options, template, block) # Runs the Col block for the given entry. def content(entry) - entry.nil? ? '' : capture(entry, &block) + entry.nil? ? "" : capture(entry, &block) end # Renders the header cell of the Col. @@ -29,7 +27,6 @@ def html_header def html_cell(entry) tag.td(content(entry), **html_options) end - end end end diff --git a/app/helpers/dry_crud/table/sorting.rb b/app/helpers/dry_crud/table/sorting.rb index 033e110..dc8737c 100644 --- a/app/helpers/dry_crud/table/sorting.rb +++ b/app/helpers/dry_crud/table/sorting.rb @@ -1,11 +1,9 @@ module DryCrud module Table - # Provides headers with sort links. Expects a method :sortable?(attr) # in the template/controller to tell if an attribute is sortable or not. # Extracted into an own module for convenience. module Sorting - # Create a header with sort links and a mark for the current sort # direction. def sort_header(attr, label = nil) @@ -40,10 +38,10 @@ def sort_params(attr) def current_mark(attr) if current_sort?(attr) # rubocop:disable Rails/OutputSafety - (sort_dir(attr) == 'asc' ? ' ↑' : ' ↓').html_safe + (sort_dir(attr) == "asc" ? " ↑" : " ↓").html_safe # rubocop:enable Rails/OutputSafety else - '' + "" end end @@ -54,14 +52,13 @@ def current_sort?(attr) # The sort direction to use in the sort link for the given attribute. def sort_dir(attr) - current_sort?(attr) && params[:sort_dir] == 'asc' ? 'desc' : 'asc' + current_sort?(attr) && params[:sort_dir] == "asc" ? "desc" : "asc" end # Delegate to template. def params template.params end - end end end diff --git a/app/helpers/form_helper.rb b/app/helpers/form_helper.rb index 7736a54..78a231f 100644 --- a/app/helpers/form_helper.rb +++ b/app/helpers/form_helper.rb @@ -6,12 +6,11 @@ # * #crud_form - A #standard_form for the current +entry+, with the given # attributes or default. module FormHelper - # Renders a form using Crud::FormBuilder. def plain_form(object, **options, &block) options[:html] ||= {} - add_css_class(options[:html], 'form-horizontal') - options[:html][:role] ||= 'form' + add_css_class(options[:html], "form-horizontal") + options[:html][:role] ||= "form" options[:builder] ||= DryCrud::Form::Builder options[:cancel_url] ||= polymorphic_path(object, returning: true) @@ -25,13 +24,13 @@ def plain_form(object, **options, &block) # if present. An options hash may be given as the last argument. def standard_form(object, *attrs, **options, &block) plain_form(object, **options) do |form| - content = [form.error_messages] + content = [ form.error_messages ] content << if block_given? capture(form, &block) - else + else form.labeled_input_fields(*attrs) - end + end content << form.standard_actions safe_join(content) @@ -45,5 +44,4 @@ def crud_form(*attrs, **options, &block) attrs = default_crud_attrs - %i[created_at updated_at] if attrs.blank? standard_form(path_args(entry), *attrs, **options, &block) end - end diff --git a/app/helpers/format_helper.rb b/app/helpers/format_helper.rb index 299b964..660d002 100644 --- a/app/helpers/format_helper.rb +++ b/app/helpers/format_helper.rb @@ -6,19 +6,18 @@ # Futher helpers standartize the layout of multiple attributes (#render_attrs), # values with labels (#labeled) and simple lists. module FormatHelper - # Formats a basic value based on its Ruby class. def f(value) case value when Float, BigDecimal - number_with_precision(value, precision: t('number.format.precision'), - delimiter: t('number.format.delimiter')) + number_with_precision(value, precision: t("number.format.precision"), + delimiter: t("number.format.delimiter")) when Integer - number_with_delimiter(value, delimiter: t('number.format.delimiter')) + number_with_delimiter(value, delimiter: t("number.format.delimiter")) when Date then l(value) when Time then "#{l(value.to_date)} #{l(value, format: :time)}" - when true then t('global.yes') - when false then t('global.no') + when true then t("global.yes") + when false then t("global.no") when nil then UtilityHelper::EMPTY_STRING else value.to_s end @@ -47,7 +46,7 @@ def simple_list(items, **ul_options) # Renders a list of attributes with label and value for a given object. # Optionally surrounded with a div. def render_attrs(obj, *attrs) - content_tag_nested(:dl, attrs, class: 'dl-horizontal') do |a| + content_tag_nested(:dl, attrs, class: "dl-horizontal") do |a| labeled_attr(obj, a) end end @@ -61,14 +60,14 @@ def labeled_attr(obj, attr) # presentation. def labeled(label, content = nil, &block) content = capture(&block) if block_given? - render('shared/labeled', label: label, content: content) + render("shared/labeled", label: label, content: content) end # Transform the given text into a form as used by labels or table headers. def captionize(text, clazz = nil) text = text.to_s if clazz.respond_to?(:human_attribute_name) - text_without_id = text.end_with?('_ids') ? text[0..-5].pluralize : text + text_without_id = text.end_with?("_ids") ? text[0..-5].pluralize : text clazz.human_attribute_name(text_without_id) else text.humanize.titleize @@ -80,7 +79,7 @@ def captionize(text, clazz = nil) # Checks whether a format_{class}_{attr} or format_{attr} helper method is # defined and calls it if is. def format_with_helper(obj, attr) - class_name = obj.class.name.underscore.tr('/', '_') + class_name = obj.class.name.underscore.tr("/", "_") format_type_attr_method = :"format_#{class_name}_#{attr}" format_attr_method = :"format_#{attr}" @@ -123,7 +122,7 @@ def format_type(obj, attr) when :decimal number_with_precision(val.to_s.to_f, precision: column_property(obj, attr, :scale), - delimiter: t('number.format.delimiter')) + delimiter: t("number.format.delimiter")) else f(val) end end @@ -161,5 +160,4 @@ def assoc_link(assoc, val) def assoc_link?(_assoc, val) respond_to?(:"#{val.class.model_name.singular_route_key}_path") end - end diff --git a/app/helpers/i18n_helper.rb b/app/helpers/i18n_helper.rb index 7f28253..ae87c57 100644 --- a/app/helpers/i18n_helper.rb +++ b/app/helpers/i18n_helper.rb @@ -1,7 +1,6 @@ # Translation helpers extending the Rails +translate+ helper to support # translation inheritance over the controller class hierarchy. module I18nHelper - # Translates the passed key by looking it up over the controller hierarchy. # The key is searched in the following order: # - {controller}.{current_partial}.{key} @@ -13,7 +12,7 @@ module I18nHelper # - ... # - global.{key} def translate_inheritable(key, **variables) - partial = defined?(@virtual_path) ? @virtual_path.gsub(/.*\/_?/, '') : nil + partial = defined?(@virtual_path) ? @virtual_path.gsub(/.*\/_?/, "") : nil defaults = inheritable_translation_defaults(key, partial) variables[:default] ||= defaults t(defaults.shift, **variables) @@ -30,8 +29,8 @@ def translate_inheritable(key, **variables) # - global.associations.{key} def translate_association(key, assoc = nil, **variables) if assoc && assoc.options[:polymorphic].nil? - variables[:default] ||= [association_klass_key(assoc, key).to_sym, - :"global.associations.#{key}"] + variables[:default] ||= [ association_klass_key(assoc, key).to_sym, + :"global.associations.#{key}" ] t(association_owner_key(assoc, key), **variables) else t("global.associations.#{key}", **variables) @@ -44,20 +43,20 @@ def translate_association(key, assoc = nil, **variables) # General translation key based on the klass of the association. def association_klass_key(assoc, key) - k = 'activerecord.associations.' + k = "activerecord.associations." k << assoc.klass.model_name.singular - k << '.' + k << "." k << key.to_s end # Specific translation key based on the owner model and the name # of the association. def association_owner_key(assoc, key) - k = 'activerecord.associations.models.' + k = "activerecord.associations.models." k << assoc.active_record.model_name.singular - k << '.' + k << "." k << assoc.name.to_s - k << '.' + k << "." k << key.to_s end @@ -79,5 +78,4 @@ def append_controller_translation_keys(defaults, folder, partial, key) defaults << :"#{folder}.#{action_name}.#{key}" defaults << :"#{folder}.global.#{key}" end - end diff --git a/app/helpers/table_helper.rb b/app/helpers/table_helper.rb index 25c369b..7d39411 100644 --- a/app/helpers/table_helper.rb +++ b/app/helpers/table_helper.rb @@ -7,14 +7,13 @@ # * #crud_table - A sortable #plain_table for the current +entries+, with the # given attributes or default and the standard crud action links. module TableHelper - # Renders a table for the given entries. One column is rendered for each # attribute passed. If a block is given, the columns defined therein are # appended to the attribute columns. # If entries is empty, an appropriate message is rendered. # An options hash may be given as the last argument. def plain_table(entries, *attrs, **options) - add_css_class(options, 'table table-striped table-hover') + add_css_class(options, "table table-striped table-hover") builder = options.delete(:builder) || DryCrud::Table::Builder builder.table(entries, self, **options) do |t| t.attrs(*attrs) @@ -29,7 +28,7 @@ def plain_table_or_message(entries, *attrs, **options, &block) if entries.present? plain_table(entries, *attrs, **options, &block) else - tag.div(ti(:no_list_entries), class: 'table') + tag.div(ti(:no_list_entries), class: "table") end end @@ -77,5 +76,4 @@ def attrs_or_default(attrs) attrs end end - end diff --git a/app/helpers/utility_helper.rb b/app/helpers/utility_helper.rb index b6d52c3..5be2ffa 100644 --- a/app/helpers/utility_helper.rb +++ b/app/helpers/utility_helper.rb @@ -1,10 +1,9 @@ -require 'English' +require "English" # View helpers for basic functions used in various other helpers. module UtilityHelper - # non-breaking space asserts better css. - EMPTY_STRING = ' '.html_safe.freeze + EMPTY_STRING = " ".html_safe.freeze # Render a content tag with the collected contents rendered # by &block for each item in collection. @@ -21,8 +20,8 @@ def safe_join(array, sep = $OUTPUT_FIELD_SEPARATOR, &block) # Returns the css class for the given flash level. def flash_class(level) case level - when :notice then 'success' - when :alert then 'error' + when :notice then "success" + when :alert then "error" else level.to_s end end @@ -72,13 +71,12 @@ def association(obj, attr, *macros) # Returns the name of the attr and it's corresponding field def assoc_and_id_attr(attr) attr = attr.to_s - if attr.end_with?('_id') - [attr[0..-4], attr] - elsif attr.end_with?('_ids') - [attr[0..-5].pluralize, attr] + if attr.end_with?("_id") + [ attr[0..-4], attr ] + elsif attr.end_with?("_ids") + [ attr[0..-5].pluralize, attr ] else - [attr, "#{attr}_id"] + [ attr, "#{attr}_id" ] end end - end diff --git a/dry_crud.gemspec b/dry_crud.gemspec index ffa92b5..366629f 100644 --- a/dry_crud.gemspec +++ b/dry_crud.gemspec @@ -1,4 +1,5 @@ # encoding: UTF-8 + require 'rubygems' require 'rake' require 'date' diff --git a/lib/dry_crud.rb b/lib/dry_crud.rb index 0b1fa92..eea5f9a 100644 --- a/lib/dry_crud.rb +++ b/lib/dry_crud.rb @@ -1,4 +1,4 @@ -require 'dry_crud/engine' +require "dry_crud/engine" # Base namespace module DryCrud diff --git a/lib/dry_crud/engine.rb b/lib/dry_crud/engine.rb index b56509c..8d0bfcd 100644 --- a/lib/dry_crud/engine.rb +++ b/lib/dry_crud/engine.rb @@ -1,10 +1,9 @@ module DryCrud # Dry Crud Rails engine class Engine < Rails::Engine - # Fields with errors are directly styled in DryCrud::FormBuilder. # Rails should just output the plain html tag. - initializer 'dry_crud.field_error_proc' do |_app| + initializer "dry_crud.field_error_proc" do |_app| ActionView::Base.field_error_proc = proc { |html_tag, _instance| html_tag } end @@ -21,6 +20,5 @@ class Engine < Rails::Engine paths.prepend(dry_crud_helpers) end end - end end diff --git a/lib/generators/dry_crud/dry_crud_generator.rb b/lib/generators/dry_crud/dry_crud_generator.rb index 73a0d8b..3e33c39 100644 --- a/lib/generators/dry_crud/dry_crud_generator.rb +++ b/lib/generators/dry_crud/dry_crud_generator.rb @@ -1,15 +1,15 @@ begin - require 'generators/dry_crud/dry_crud_generator_base' + require "generators/dry_crud/dry_crud_generator_base" rescue LoadError => _e # ok, we are in the rake task end # Copies all dry_crud files to the rails application. class DryCrudGenerator < DryCrudGeneratorBase - desc 'Copy all dry_crud files to the application.' + desc "Copy all dry_crud files to the application." - class_options %w[templates -t] => 'erb' - class_options %w[tests] => 'testunit' + class_options %w[templates -t] => "erb" + class_options %w[tests] => "testunit" # copy everything to application def install_dry_crud @@ -19,7 +19,7 @@ def install_dry_crud copy_crud_test_model end - readme 'INSTALL' + readme "INSTALL" end private @@ -27,29 +27,29 @@ def install_dry_crud def should_copy?(file_source) !file_source.end_with?(exclude_template) && !file_source.start_with?(exclude_test_dir) && - file_source != 'INSTALL' + file_source != "INSTALL" end def copy_crud_test_model - unless exclude_test_dir == 'spec' - template(File.join('test', 'support', 'crud_test_model.rb'), - File.join('spec', 'support', 'crud_test_model.rb')) - template(File.join('test', 'support', 'crud_test_models_controller.rb'), - File.join('spec', 'support', 'crud_test_models_controller.rb')) - template(File.join('test', 'support', 'crud_test_helper.rb'), - File.join('spec', 'support', 'crud_test_helper.rb')) + unless exclude_test_dir == "spec" + template(File.join("test", "support", "crud_test_model.rb"), + File.join("spec", "support", "crud_test_model.rb")) + template(File.join("test", "support", "crud_test_models_controller.rb"), + File.join("spec", "support", "crud_test_models_controller.rb")) + template(File.join("test", "support", "crud_test_helper.rb"), + File.join("spec", "support", "crud_test_helper.rb")) end end def exclude_template - options[:templates].casecmp('haml').zero? ? '.erb' : '.haml' + options[:templates].casecmp("haml").zero? ? ".erb" : ".haml" end def exclude_test_dir case options[:tests].downcase - when 'rspec' then 'test' - when 'all' then 'exclude_nothing' - else 'spec' + when "rspec" then "test" + when "all" then "exclude_nothing" + else "spec" end end end diff --git a/lib/generators/dry_crud/dry_crud_generator_base.rb b/lib/generators/dry_crud/dry_crud_generator_base.rb index 8fcb052..9f2560c 100644 --- a/lib/generators/dry_crud/dry_crud_generator_base.rb +++ b/lib/generators/dry_crud/dry_crud_generator_base.rb @@ -1,31 +1,31 @@ -require 'rails/generators' +require "rails/generators" # Generates all dry crud files class DryCrudGeneratorBase < Rails::Generators::Base def self.template_root - File.join(File.dirname(__FILE__), 'templates') + File.join(File.dirname(__FILE__), "templates") end def self.gem_root - File.join(File.dirname(__FILE__), '..', '..', '..') + File.join(File.dirname(__FILE__), "..", "..", "..") end def self.source_paths - [gem_root, - template_root] + [ gem_root, + template_root ] end private def all_template_files { self.class.gem_root => - template_files(self.class.gem_root, 'app', 'config'), + template_files(self.class.gem_root, "app", "config"), self.class.template_root => template_files(self.class.template_root) } end def template_files(root, *folders) - pattern = File.join('**', '**') + pattern = File.join("**", "**") pattern = File.join("{#{folders.join(',')}}", pattern) if folders.present? Dir.chdir(root) do Dir.glob(pattern).sort.reject { |f| File.directory?(f) } @@ -47,7 +47,7 @@ def should_copy?(_file_source) end def copy_file_source(file_source) - if file_source.end_with?('.erb') + if file_source.end_with?(".erb") copy_file(file_source) else template(file_source) diff --git a/lib/generators/dry_crud/file_generator.rb b/lib/generators/dry_crud/file_generator.rb index 0a6e2b6..2c774e5 100644 --- a/lib/generators/dry_crud/file_generator.rb +++ b/lib/generators/dry_crud/file_generator.rb @@ -1,16 +1,16 @@ -require 'generators/dry_crud/dry_crud_generator_base' +require "generators/dry_crud/dry_crud_generator_base" module DryCrud # Copies one file of dry_crud to the rails application. class FileGenerator < ::DryCrudGeneratorBase desc "Copy one file from dry_crud to the application.\n" \ - 'FILENAME is a part of the name of the file to copy. ' \ - 'Must match exactly one file.' + "FILENAME is a part of the name of the file to copy. " \ + "Must match exactly one file." argument :filename, type: :string, - desc: 'Name or part of the filename to copy. ' \ - 'Must match exactly one file.' + desc: "Name or part of the filename to copy. " \ + "Must match exactly one file." # rubocop:disable Rails/Output def copy_matching_file @@ -21,7 +21,7 @@ def copy_matching_file when 0 puts "No file containing '#{filename}' found in dry_crud." else - puts 'Please be more specific. ' \ + puts "Please be more specific. " \ "All the following files match '#{filename}':" files.each do |f| puts " * #{f}" diff --git a/lib/generators/dry_crud/templates/config/initializers/field_error_proc.rb b/lib/generators/dry_crud/templates/config/initializers/field_error_proc.rb index bdf5728..3bfd70a 100644 --- a/lib/generators/dry_crud/templates/config/initializers/field_error_proc.rb +++ b/lib/generators/dry_crud/templates/config/initializers/field_error_proc.rb @@ -2,4 +2,4 @@ # Fields with errors are directly styled in Crud::FormBuilder. # Rails should just output the plain html tag. -ActionView::Base.field_error_proc = proc { |html_tag, instance| html_tag } \ No newline at end of file +ActionView::Base.field_error_proc = proc { |html_tag, instance| html_tag } diff --git a/lib/generators/dry_crud/templates/spec/controllers/crud_test_models_controller_spec.rb b/lib/generators/dry_crud/templates/spec/controllers/crud_test_models_controller_spec.rb index 0b8c438..72c414f 100644 --- a/lib/generators/dry_crud/templates/spec/controllers/crud_test_models_controller_spec.rb +++ b/lib/generators/dry_crud/templates/spec/controllers/crud_test_models_controller_spec.rb @@ -1,4 +1,4 @@ -require 'rails_helper' +require "rails_helper" # Tests all actions of the CrudController based on a dummy model # (CrudTestModel). This is useful to test the general behavior @@ -17,201 +17,201 @@ before { special_routing } - include_examples 'crud controller', {} + include_examples "crud controller", {} let(:test_entry) { crud_test_models(:AAAAA) } let(:new_entry_attrs) do - { name: 'foo', + { name: "foo", children: 42, companion_id: 3, rating: 8.5, income: 2.42, - birthdate: '31-12-1999'.to_date, + birthdate: "31-12-1999".to_date, human: true, remarks: "some custom\n\tremarks" } end let(:edit_entry_attrs) do - { name: 'foo', + { name: "foo", children: 42, rating: 8.5, income: 2.42, - birthdate: '31-12-1999'.to_date, + birthdate: "31-12-1999".to_date, human: true, remarks: "some custom\n\tremarks" } end - describe 'setup' do - it 'model count is correct' do + describe "setup" do + it "model count is correct" do expect(CrudTestModel.count).to eq(6) end - it 'has models_label' do - expect(controller.models_label).to eq('Crud Test Models') + it "has models_label" do + expect(controller.models_label).to eq("Crud Test Models") end - it 'has models_label singular' do - expect(controller.models_label(plural: false)).to eq('Crud Test Model') + it "has models_label singular" do + expect(controller.models_label(plural: false)).to eq("Crud Test Model") end end describe_action :get, :index do - context '.html', format: :html do - context 'plain', combine: 'ihp' do - it 'contains all entries' do + context ".html", format: :html do + context "plain", combine: "ihp" do + it "contains all entries" do expect(entries.size).to eq(6) end - it 'session has empty list_params' do + it "session has empty list_params" do expect(session[:list_params]).to eq({}) end - it 'provides entries helper method' do + it "provides entries helper method" do expect(entries).to be(controller.send(:entries)) end end - context 'search' do + context "search" do let(:params) { { q: search_value } } - context 'regular', combine: 'ihse' do - it 'entries only contain test_entry' do - expect(entries).to eq([test_entry]) + context "regular", combine: "ihse" do + it "entries only contain test_entry" do + expect(entries).to eq([ test_entry ]) end - it 'session has query list param' do - expect(session[:list_params]['/crud_test_models.html']) - .to eq('q' => 'AAAA') + it "session has query list param" do + expect(session[:list_params]["/crud_test_models.html"]) + .to eq("q" => "AAAA") end end - context 'with custom options', combine: 'ihsec' do - let(:params) { { q: 'DDD', filter: true } } + context "with custom options", combine: "ihsec" do + let(:params) { { q: "DDD", filter: true } } it_is_expected_to_respond - it 'entries have one item' do - expect(entries).to eq([CrudTestModel.find_by(name: 'BBBBB')]) + it "entries have one item" do + expect(entries).to eq([ CrudTestModel.find_by(name: "BBBBB") ]) end - it 'session has query list param' do - expect(session[:list_params]['/crud_test_models.html']) - .to eq('q' => 'DDD') + it "session has query list param" do + expect(session[:list_params]["/crud_test_models.html"]) + .to eq("q" => "DDD") end end end - context 'sort' do - context 'for given column', combine: 'ihsog' do - let(:params) { { sort: 'children', sort_dir: 'asc' } } + context "sort" do + context "for given column", combine: "ihsog" do + let(:params) { { sort: "children", sort_dir: "asc" } } it_is_expected_to_respond - it 'entries are in correct order' do + it "entries are in correct order" do expect(entries).to eq(CrudTestModel.all.sort_by(&:children)) end - it 'session has sort list param' do - expect(session[:list_params]['/crud_test_models.html']).to eq( - 'sort' => 'children', 'sort_dir' => 'asc' + it "session has sort list param" do + expect(session[:list_params]["/crud_test_models.html"]).to eq( + "sort" => "children", "sort_dir" => "asc" ) end end - context 'for virtual column', combine: 'ihsov' do - let(:params) { { sort: 'chatty', sort_dir: 'desc' } } + context "for virtual column", combine: "ihsov" do + let(:params) { { sort: "chatty", sort_dir: "desc" } } it_is_expected_to_respond - it 'entries are in correct order' do + it "entries are in correct order" do names = entries.map(&:name) - assert names.index('BBBBB') < names.index('AAAAA') - assert names.index('BBBBB') < names.index('DDDDD') - assert names.index('EEEEE') < names.index('AAAAA') - assert names.index('EEEEE') < names.index('DDDDD') - assert names.index('AAAAA') < names.index('CCCCC') - assert names.index('DDDDD') < names.index('CCCCC') + assert names.index("BBBBB") < names.index("AAAAA") + assert names.index("BBBBB") < names.index("DDDDD") + assert names.index("EEEEE") < names.index("AAAAA") + assert names.index("EEEEE") < names.index("DDDDD") + assert names.index("AAAAA") < names.index("CCCCC") + assert names.index("DDDDD") < names.index("CCCCC") end - it 'session has sort list param' do - expect(session[:list_params]['/crud_test_models.html']).to eq( - 'sort' => 'chatty', 'sort_dir' => 'desc' + it "session has sort list param" do + expect(session[:list_params]["/crud_test_models.html"]).to eq( + "sort" => "chatty", "sort_dir" => "desc" ) end end - context 'with search', combine: 'ihsose' do + context "with search", combine: "ihsose" do let(:params) do - { q: 'DDD', sort: 'chatty', sort_dir: 'asc' } + { q: "DDD", sort: "chatty", sort_dir: "asc" } end it_is_expected_to_respond - it 'entries are in correct order' do + it "entries are in correct order" do expect(entries.map(&:name)).to eq(%w[CCCCC DDDDD BBBBB]) end - it 'session has sort list param' do - expect(session[:list_params]['/crud_test_models.html']).to eq( - 'q' => 'DDD', 'sort' => 'chatty', 'sort_dir' => 'asc' + it "session has sort list param" do + expect(session[:list_params]["/crud_test_models.html"]).to eq( + "q" => "DDD", "sort" => "chatty", "sort_dir" => "asc" ) end end end - context 'with custom options', combine: 'ihsoco' do + context "with custom options", combine: "ihsoco" do let(:params) { { filter: true } } it_is_expected_to_respond - context 'entries' do + context "entries" do subject { entries } it { expect(subject.size).to eq(2) } it { is_expected.to eq(entries.sort_by(&:children).reverse) } end end - context 'returning', perform_request: false do + context "returning", perform_request: false do before do session[:list_params] = {} - session[:list_params]['/crud_test_models'] = - { 'q' => 'DDD', 'sort' => 'chatty', 'sort_dir' => 'desc' } + session[:list_params]["/crud_test_models"] = + { "q" => "DDD", "sort" => "chatty", "sort_dir" => "desc" } get :index, params: { returning: true } end it_is_expected_to_respond - it 'entries are in correct order' do + it "entries are in correct order" do expect(entries.map(&:name)).to eq(%w[BBBBB DDDDD CCCCC]) end - it 'params are set' do - expect(controller.params[:q]).to eq('DDD') - expect(controller.params[:sort]).to eq('chatty') - expect(controller.params[:sort_dir]).to eq('desc') + it "params are set" do + expect(controller.params[:q]).to eq("DDD") + expect(controller.params[:sort]).to eq("chatty") + expect(controller.params[:sort_dir]).to eq("desc") end end end - context '.js', format: :js, combine: 'ijs' do + context ".js", format: :js, combine: "ijs" do it_is_expected_to_respond - it { expect(response.body).to eq('index js') } + it { expect(response.body).to eq("index js") } end end describe_action :get, :new do - context 'plain', combine: 'new' do - it 'assigns companions' do + context "plain", combine: "new" do + it "assigns companions" do expect(ivar(:companions)).to be_present end - it 'calls two render callbacks' do + it "calls two render callbacks" do expect(controller.called_callbacks).to eq( %i[before_render_new before_render_form] ) end end - context 'with before_render callback redirect', + context "with before_render callback redirect", perform_request: false do before do controller.should_redirect = true @@ -220,7 +220,7 @@ it { is_expected.to redirect_to(crud_test_models_path) } - it 'does not set companions' do + it "does not set companions" do expect(ivar(:companions)).to be_nil end end @@ -229,44 +229,44 @@ describe_action :post, :create do let(:params) { { model_identifier => new_entry_attrs } } - it 'calls the correct callbacks' do + it "calls the correct callbacks" do expect(controller.called_callbacks).to eq( %i[before_create before_save after_save after_create] ) end - context 'with before callback' do + context "with before callback" do let(:params) do - { crud_test_model: { name: 'illegal', children: 2 } } + { crud_test_model: { name: "illegal", children: 2 } } end - it 'does not create entry', perform_request: false do + it "does not create entry", perform_request: false do expect { perform_request }.to change { CrudTestModel.count }.by(0) end - context 'plain', combine: 'chcp' do + context "plain", combine: "chcp" do it_is_expected_to_respond it_is_expected_to_persist_entry(persist: false) it_is_expected_to_have_flash(:alert) - it 'sets entry name' do - expect(entry.name).to eq('illegal') + it "sets entry name" do + expect(entry.name).to eq("illegal") end - it 'assigns companions' do + it "assigns companions" do expect(ivar(:companions)).to be_present end - it 'calls the correct callbacks' do + it "calls the correct callbacks" do expect(controller.called_callbacks).to eq( %i[before_render_new before_render_form] ) end end - context 'redirect', perform_request: false do + context "redirect", perform_request: false do before { controller.should_redirect = true } - it 'does not create entry' do + it "does not create entry" do expect { perform_request }.to change { CrudTestModel.count }.by(0) end @@ -275,32 +275,32 @@ is_expected.to redirect_to(crud_test_models_path) end - it 'calls no callbacks' do + it "calls no callbacks" do perform_request expect(controller.called_callbacks).to be_nil end end end - context 'with invalid params' do + context "with invalid params" do let(:params) { { crud_test_model: { children: 2 } } } - context '.html' do - it 'does not create entry', perform_request: false do + context ".html" do + it "does not create entry", perform_request: false do expect { perform_request }.to change { CrudTestModel.count }.by(0) end - context 'plain', combine: 'chip' do + context "plain", combine: "chip" do it_is_expected_to_respond it_is_expected_to_persist_entry(persist: false) it_is_expected_to_not_have_flash(:notice) it_is_expected_to_not_have_flash(:alert) - it 'assigns companions' do + it "assigns companions" do expect(ivar(:companions)).to be_present end - it 'calls the correct callbacks' do + it "calls the correct callbacks" do expect(controller.called_callbacks).to eq( %i[before_create before_save before_render_new before_render_form] @@ -309,23 +309,23 @@ end end - context '.json', format: :json do - it 'does not create entry', perform_request: false do + context ".json", format: :json do + it "does not create entry", perform_request: false do expect { perform_request }.to change { CrudTestModel.count }.by(0) end - context 'plain', combine: 'cjcb' do + context "plain", combine: "cjcb" do it_is_expected_to_respond(422) it_is_expected_to_persist_entry(persist: false) it_is_expected_to_not_have_flash(:notice) it_is_expected_to_not_have_flash(:alert) it_is_expected_to_render_json - it 'does not assign companions' do + it "does not assign companions" do expect(ivar(:companions)).to be_nil end - it 'calls the correct callbacks' do + it "calls the correct callbacks" do expect(controller.called_callbacks).to eq( %i[before_create before_save] ) @@ -336,7 +336,7 @@ end describe_action :get, :edit, id: true do - it 'calls the correct callbacks' do + it "calls the correct callbacks" do expect(controller.called_callbacks).to eq( %i[before_render_edit before_render_form] ) @@ -346,52 +346,52 @@ describe_action :put, :update, id: true do let(:params) { { model_identifier => edit_entry_attrs } } - it 'calls the correct callbacks' do + it "calls the correct callbacks" do expect(controller.called_callbacks).to eq( %i[before_update before_save after_save after_update] ) end - context 'with invalid params' do + context "with invalid params" do let(:params) do { crud_test_model: { rating: 20, - other_ids: [OtherCrudTestModel.first.id] + other_ids: [ OtherCrudTestModel.first.id ] } } end - context '.html', combine: 'uhivp' do + context ".html", combine: "uhivp" do it_is_expected_to_respond it_is_expected_to_not_have_flash(:notice) - it 'changes entry' do + it "changes entry" do expect(entry).to be_changed end - it 'sets entry rating' do + it "sets entry rating" do expect(entry.rating).to eq(20) end - it 'calls the correct callbacks' do + it "calls the correct callbacks" do expect(controller.called_callbacks).to eq( %i[before_update before_save before_render_edit before_render_form] ) end - it 'does not update has_many ids' do + it "does not update has_many ids" do expect(test_entry.reload.other_ids).to eq([]) end end - context '.json', format: :json, combine: 'ujivp' do + context ".json", format: :json, combine: "ujivp" do it_is_expected_to_respond(422) it_is_expected_to_not_have_flash(:notice) it_is_expected_to_render_json - it 'calls the correct callbacks' do + it "calls the correct callbacks" do expect(controller.called_callbacks).to eq( %i[before_update before_save] ) @@ -401,23 +401,23 @@ end describe_action :delete, :destroy, id: true do - it 'calls the correct callbacks' do + it "calls the correct callbacks" do expect(controller.called_callbacks).to eq( %i[before_destroy after_destroy] ) end - context 'with failure' do + context "with failure" do let(:test_entry) { crud_test_models(:BBBBB) } - context '.html' do - it 'does not delete entry from database', + context ".html" do + it "does not delete entry from database", perform_request: false do expect { perform_request }.not_to(change { CrudTestModel.count }) end - it 'redirects to referer', + it "redirects to referer", perform_request: false do - ref = @request.env['HTTP_REFERER'] = crud_test_model_url(test_entry) + ref = @request.env["HTTP_REFERER"] = crud_test_model_url(test_entry) perform_request is_expected.to redirect_to(ref) end @@ -426,29 +426,29 @@ it_is_expected_to_not_have_flash(:notice) end - context '.json', format: :json, combine: 'djf' do + context ".json", format: :json, combine: "djf" do it_is_expected_to_respond(422) it_is_expected_to_not_have_flash(:notice) it_is_expected_to_render_json end - context 'callback', perform_request: false do + context "callback", perform_request: false do before do # rubocop:disable Rails/SkipsModelValidations - test_entry.update_attribute(:name, 'illegal') + test_entry.update_attribute(:name, "illegal") # rubocop:enable Rails/SkipsModelValidations end - it 'does not delete entry from database' do + it "does not delete entry from database" do expect { perform_request }.not_to(change { CrudTestModel.count }) end - it 'redirects to index' do + it "redirects to index" do perform_request is_expected.to redirect_to(crud_test_models_path(returning: true)) end - it 'has flash alert' do + it "has flash alert" do perform_request expect(flash[:alert]).to match(/illegal name/) end diff --git a/lib/generators/dry_crud/templates/spec/helpers/dry_crud/form/builder_spec.rb b/lib/generators/dry_crud/templates/spec/helpers/dry_crud/form/builder_spec.rb index e494b21..3719d60 100644 --- a/lib/generators/dry_crud/templates/spec/helpers/dry_crud/form/builder_spec.rb +++ b/lib/generators/dry_crud/templates/spec/helpers/dry_crud/form/builder_spec.rb @@ -1,7 +1,6 @@ -require 'rails_helper' - -describe 'DryCrud::Form::Builder' do +require "rails_helper" +describe "DryCrud::Form::Builder" do include FormatHelper include FormHelper include UtilityHelper @@ -19,12 +18,11 @@ let(:entry) { CrudTestModel.first } let(:form) { DryCrud::Form::Builder.new(:entry, entry, self, {}) } - describe '#input_field' do - - it 'dispatches name attr to string field' do + describe "#input_field" do + it "dispatches name attr to string field" do expect(form).to receive(:string_field) - .with(:name, required: 'required') - .and_return('') + .with(:name, required: "required") + .and_return("") form.input_field(:name) end @@ -48,134 +46,132 @@ it { expect(form.input_field(attr)).to be_html_safe } end - end - describe '#labeled_input_fields' do + describe "#labeled_input_fields" do subject { form.labeled_input_fields(:name, :remarks, :children) } it { is_expected.to be_html_safe } - it { is_expected.to include(form.input_field(:name, required: 'required')) } + it { is_expected.to include(form.input_field(:name, required: "required")) } it { is_expected.to include(form.input_field(:remarks)) } it { is_expected.to include(form.input_field(:children)) } end - describe '#labeled_input_field' do - context 'when required' do + describe "#labeled_input_field" do + context "when required" do subject { form.labeled_input_field(:name) } - it { is_expected.to include('input-group-text') } + it { is_expected.to include("input-group-text") } end - context 'when not required' do + context "when not required" do subject { form.labeled_input_field(:remarks) } - it { is_expected.not_to include('input-group-text') } + it { is_expected.not_to include("input-group-text") } end - context 'with help text' do - subject { form.labeled_input_field(:name, help: 'Some Help') } - it { is_expected.to include(form.help_block('Some Help')) } + context "with help text" do + subject { form.labeled_input_field(:name, help: "Some Help") } + it { is_expected.to include(form.help_block("Some Help")) } end end - describe '#belongs_to_field' do - it 'has all options by default' do + describe "#belongs_to_field" do + it "has all options by default" do f = form.belongs_to_field(:companion_id) expect_n_options(f, 7) end - it 'with has options from :list option' do + it "with has options from :list option" do list = CrudTestModel.all f = form.belongs_to_field(:companion_id, - list: [list.first, list.second]) + list: [ list.first, list.second ]) expect_n_options(f, 3) end - it 'with empty instance list has no select' do + it "with empty instance list has no select" do assign(:companions, []) @companions = [] f = form.belongs_to_field(:companion_id) - expect(f).to match t('global.associations.none_available') + expect(f).to match t("global.associations.none_available") expect_n_options(f, 0) end end - describe '#has_and_belongs_to_many_field' do + describe "#has_and_belongs_to_many_field" do let(:others) { OtherCrudTestModel.all[0..1] } - it 'has all options by default' do + it "has all options by default" do f = form.has_many_field(:other_ids) expect_n_options(f, 6) end - it 'uses options from :list option if given' do + it "uses options from :list option if given" do f = form.has_many_field(:other_ids, list: others) expect_n_options(f, 2) end - it 'uses options form instance variable if given' do + it "uses options form instance variable if given" do assign(:others, others) @others = others f = form.has_many_field(:other_ids) expect_n_options(f, 2) end - it 'displays a message for an empty list' do + it "displays a message for an empty list" do @others = [] f = form.has_many_field(:other_ids) - expect(f).to match t('global.associations.none_available') + expect(f).to match t("global.associations.none_available") expect_n_options(f, 0) end end - describe '#string_field' do - it 'sets maxlength if attr has a limit' do + describe "#string_field" do + it "sets maxlength if attr has a limit" do expect(form.string_field(:name)).to match(/maxlength="50"/) end end - describe '#label' do - context 'only with attr' do + describe "#label" do + context "only with attr" do subject { form.label(:gugus_dada) } it { is_expected.to be_html_safe } - it 'provides the same interface as rails' do + it "provides the same interface as rails" do is_expected.to match(/label [^>]*for.+Gugus dada/) end end - context 'with attr and text' do - subject { form.label(:gugus_dada, 'hoho') } + context "with attr and text" do + subject { form.label(:gugus_dada, "hoho") } it { is_expected.to be_html_safe } - it 'provides the same interface as rails' do + it "provides the same interface as rails" do is_expected.to match(/label [^>]*for.+hoho/) end end - end - describe '#labeled' do - context 'in labeled_ method' do + describe "#labeled" do + context "in labeled_ method" do subject { form.labeled_string_field(:name) } it { is_expected.to be_html_safe } - it 'provides the same interface as rails' do + it "provides the same interface as rails" do is_expected.to match(/label [^>]*for.+input/m) end end - context 'with custom content in argument' do + context "with custom content in argument" do subject do - form.labeled('gugus', "".html_safe) + form.labeled("gugus", "".html_safe) end it { is_expected.to be_html_safe } it { is_expected.to match(/label [^>]*for.+".html_safe end end @@ -184,20 +180,20 @@ it { is_expected.to match(/label [^>]*for.+".html_safe, - caption: 'Caption') + caption: "Caption") end it { is_expected.to be_html_safe } it { is_expected.to match(/label [^>]*for.+>Caption<\/label>.*".html_safe end end @@ -207,26 +203,25 @@ end end - it 'handles missing methods' do + it "handles missing methods" do expect { form.blabla }.to raise_error(NoMethodError) end - context '#respond_to?' do - it 'returns false for non existing methods' do + context "#respond_to?" do + it "returns false for non existing methods" do expect(form.respond_to?(:blabla)).to be false end - it 'returns true for existing methods' do + it "returns true for existing methods" do expect(form.respond_to?(:text_field)).to be true end - it 'returns true for labeled_ methods' do + it "returns true for labeled_ methods" do expect(form.respond_to?(:labeled_text_field)).to be true end end def expect_n_options(form, count) - expect(form.scan('').size).to eq(count) + expect(form.scan("").size).to eq(count) end - end diff --git a/lib/generators/dry_crud/templates/spec/helpers/dry_crud/table/builder_spec.rb b/lib/generators/dry_crud/templates/spec/helpers/dry_crud/table/builder_spec.rb index 19115b2..a92e5a3 100644 --- a/lib/generators/dry_crud/templates/spec/helpers/dry_crud/table/builder_spec.rb +++ b/lib/generators/dry_crud/templates/spec/helpers/dry_crud/table/builder_spec.rb @@ -1,7 +1,6 @@ -require 'rails_helper' - -describe 'DryCrud::Table::Builder' do +require "rails_helper" +describe "DryCrud::Table::Builder" do include FormatHelper include UtilityHelper @@ -12,43 +11,43 @@ def format_size(obj) # :nodoc: "#{obj.size} chars" end - specify '#html_header' do + specify "#html_header" do table.attrs :upcase, :size - dom = 'UpcaseSize' + dom = "UpcaseSize" assert_dom_equal dom, table.send(:html_header) end - specify 'single attr row' do + specify "single attr row" do table.attrs :upcase, :size - dom = 'FOO3 chars' + dom = "FOO3 chars" assert_dom_equal dom, table.send(:html_row, entries.first) end - specify 'custom row' do - table.col('Header', class: 'hula') { |e| "Weights #{e.size} kg" } + specify "custom row" do + table.col("Header", class: "hula") { |e| "Weights #{e.size} kg" } dom = 'Weights 3 kg' assert_dom_equal dom, table.send(:html_row, entries.first) end - context 'attr col' do + context "attr col" do let(:col) { table.cols.first } - context 'output' do + context "output" do before { table.attrs :upcase } - it { expect(col.html_header).to eq('Upcase') } - it { expect(col.content('foo')).to eq('FOO') } - it { expect(col.html_cell('foo')).to eq('FOO') } + it { expect(col.html_header).to eq("Upcase") } + it { expect(col.content("foo")).to eq("FOO") } + it { expect(col.html_cell("foo")).to eq("FOO") } end - context 'content with custom format_size method' do + context "content with custom format_size method" do before { table.attrs :size } - it { expect(col.content('abcd')).to eq('4 chars') } + it { expect(col.content("abcd")).to eq("4 chars") } end end - specify 'two x two table' do + specify "two x two table" do dom = <<-FIN @@ -60,14 +59,14 @@ def format_size(obj) # :nodoc:
FIN - dom.gsub!(/[\n\t]/, '').gsub!(/\s{2,}/, '') + dom.gsub!(/[\n\t]/, "").gsub!(/\s{2,}/, "") table.attrs :upcase, :size assert_dom_equal dom, table.to_html end - specify 'table with before and after cells' do + specify "table with before and after cells" do dom = <<-FIN @@ -89,16 +88,16 @@ def format_size(obj) # :nodoc:
FIN - dom.gsub!(/[\n\t]/, '').gsub!(/\s{2,}/, '') + dom.gsub!(/[\n\t]/, "").gsub!(/\s{2,}/, "") - table.col('head', class: 'left') { |e| link_to e, '/' } + table.col("head", class: "left") { |e| link_to e, "/" } table.attrs :upcase, :size table.col { |e| "Never #{e}" } assert_dom_equal dom, table.to_html end - specify 'empty entries collection renders empty table' do + specify "empty entries collection renders empty table" do dom = <<-FIN @@ -108,14 +107,13 @@ def format_size(obj) # :nodoc:
FIN - dom.gsub!(/[\n\t]/, '').gsub!(/\s{2,}/, '') + dom.gsub!(/[\n\t]/, "").gsub!(/\s{2,}/, "") table = DryCrud::Table::Builder.new([], self) - table.col('head', class: 'left') { |e| link_to e, '/' } + table.col("head", class: "left") { |e| link_to e, "/" } table.attrs :upcase, :size table.col { |e| "Never #{e}" } assert_dom_equal dom, table.to_html end - end diff --git a/lib/generators/dry_crud/templates/spec/helpers/form_helper_spec.rb b/lib/generators/dry_crud/templates/spec/helpers/form_helper_spec.rb index 6cf76e9..c1eac7e 100644 --- a/lib/generators/dry_crud/templates/spec/helpers/form_helper_spec.rb +++ b/lib/generators/dry_crud/templates/spec/helpers/form_helper_spec.rb @@ -1,7 +1,6 @@ -require 'rails_helper' +require "rails_helper" describe FormHelper do - include UtilityHelper include FormatHelper include I18nHelper @@ -15,18 +14,18 @@ after(:all) { reset_db } - describe '#plain_form' do + describe "#plain_form" do subject do with_test_routing do capture do - plain_form(entry, html: { class: 'special' }) do |f| + plain_form(entry, html: { class: "special" }) do |f| f.labeled_input_fields :name, :birthdate end end end end - context 'for existing entry' do + context "for existing entry" do let(:entry) { crud_test_models(:AAAAA) } it do @@ -55,20 +54,19 @@ end end - describe '#standard_form' do - + describe "#standard_form" do subject do with_test_routing do capture do standard_form(entry, :name, :children, :birthdate, :human, - cancel_url: '/somewhere', - html: { class: 'special' }) + cancel_url: "/somewhere", + html: { class: "special" }) end end end - context 'for existing entry' do + context "for existing entry" do let(:entry) { crud_test_models(:AAAAA) } it do @@ -119,7 +117,7 @@ end end - context 'for invalid entry' do + context "for invalid entry" do let(:entry) do e = crud_test_models(:AAAAA) e.name = nil @@ -146,7 +144,7 @@ end end - describe '#crud_form' do + describe "#crud_form" do let(:entry) { CrudTestModel.first } subject do with_test_routing { crud_form } @@ -215,5 +213,4 @@ #{t('global.button.cancel')}<\/a>/x) end end - end diff --git a/lib/generators/dry_crud/templates/spec/helpers/format_helper_spec.rb b/lib/generators/dry_crud/templates/spec/helpers/format_helper_spec.rb index 0ef97d1..8e0f060 100644 --- a/lib/generators/dry_crud/templates/spec/helpers/format_helper_spec.rb +++ b/lib/generators/dry_crud/templates/spec/helpers/format_helper_spec.rb @@ -1,7 +1,6 @@ -require 'rails_helper' +require "rails_helper" describe FormatHelper do - include UtilityHelper include I18nHelper include CrudTestHelper @@ -23,9 +22,9 @@ def format_string_size(obj) # :nodoc: "#{f(obj.size)} chars" end - describe '#labeled' do - context 'regular' do - subject { labeled('label') { 'value' } } + describe "#labeled" do + context "regular" do + subject { labeled("label") { "value" } } it { is_expected.to be_html_safe } it do @@ -36,8 +35,8 @@ def format_string_size(obj) # :nodoc: end end - context 'with empty value' do - subject { labeled('label') { '' } } + context "with empty value" do + subject { labeled("label") { "" } } it { is_expected.to be_html_safe } it do @@ -45,13 +44,13 @@ def format_string_size(obj) # :nodoc: /
label<\/dt> \ #{UtilityHelper::EMPTY_STRING} - <\/dd>$/x + <\/dd>$/xo ) end end - context 'with unsafe value' do - subject { labeled('label') { 'value ' } } + context "with unsafe value" do + subject { labeled("label") { "value " } } it { is_expected.to be_html_safe } it do @@ -65,8 +64,8 @@ def format_string_size(obj) # :nodoc: end end - describe '#labeled_attr' do - subject { labeled_attr('foo', :size) } + describe "#labeled_attr" do + subject { labeled_attr("foo", :size) } it { is_expected.to be_html_safe } it do @@ -77,110 +76,108 @@ def format_string_size(obj) # :nodoc: end end - describe '#f' do - - unless ENV['NON_LOCALIZED'] # localization dependent tests - context 'Floats' do - it 'adds two digits' do - expect(f(1.0)).to eq('1.000') + describe "#f" do + unless ENV["NON_LOCALIZED"] # localization dependent tests + context "Floats" do + it "adds two digits" do + expect(f(1.0)).to eq("1.000") end - it 'truncates to two digits' do - expect(f(3.14159)).to eq('3.142') + it "truncates to two digits" do + expect(f(3.14159)).to eq("3.142") end - it 'adds delimiters' do - expect(f(12_345.6789)).to eq('12,345.679') + it "adds delimiters" do + expect(f(12_345.6789)).to eq("12,345.679") end end - context 'Booleans' do - it 'true is_expected.to print yes' do - expect(f(true)).to eq('yes') + context "Booleans" do + it "true is_expected.to print yes" do + expect(f(true)).to eq("yes") end - it 'false is_expected.to print no' do - expect(f(false)).to eq('no') + it "false is_expected.to print no" do + expect(f(false)).to eq("no") end end - context 'Dates' do - it 'prints regular date' do - expect(f(Date.new(2013, 6, 9))).to eq('2013-06-09') + context "Dates" do + it "prints regular date" do + expect(f(Date.new(2013, 6, 9))).to eq("2013-06-09") end end - context 'Times' do - it 'prints regular date' do - expect(f(Time.utc(2013, 6, 9, 21, 25))).to eq('2013-06-09 21:25') + context "Times" do + it "prints regular date" do + expect(f(Time.utc(2013, 6, 9, 21, 25))).to eq("2013-06-09 21:25") end end end - context 'nil' do - it 'prints an empty string' do + context "nil" do + it "prints an empty string" do expect(f(nil)).to eq(UtilityHelper::EMPTY_STRING) end end - context 'Strings' do - it 'prints regular strings unchanged' do - expect(f('blah blah')).to eq('blah blah') + context "Strings" do + it "prints regular strings unchanged" do + expect(f("blah blah")).to eq("blah blah") end - it 'is not html safe' do - expect(f('')).not_to be_html_safe + it "is not html safe" do + expect(f("")).not_to be_html_safe end end - end - describe '#format_attr' do - it 'uses #f' do - expect(format_attr('12.342', :to_f)).to eq(f(12.342)) + describe "#format_attr" do + it "uses #f" do + expect(format_attr("12.342", :to_f)).to eq(f(12.342)) end - it 'uses object attr format method if it exists' do - expect(format_attr('abcd', :size)).to eq('4 chars') + it "uses object attr format method if it exists" do + expect(format_attr("abcd", :size)).to eq("4 chars") end - it 'uses general attr format method if it exists' do - expect(format_attr([1, 2], :size)).to eq('2 items') + it "uses general attr format method if it exists" do + expect(format_attr([ 1, 2 ], :size)).to eq("2 items") end - it 'formats empty belongs_to' do + it "formats empty belongs_to" do expect(format_attr(crud_test_models(:AAAAA), :companion)).to eq( - t('global.associations.no_entry') + t("global.associations.no_entry") ) end - it 'formats existing belongs_to' do + it "formats existing belongs_to" do string = format_attr(crud_test_models(:BBBBB), :companion) - expect(string).to eq('AAAAA') + expect(string).to eq("AAAAA") end - it 'formats empty has_one' do + it "formats empty has_one" do expect(format_attr(crud_test_models(:FFFFF), :comrad)).to eq( - t('global.associations.no_entry') + t("global.associations.no_entry") ) end - it 'formats existing has_one' do + it "formats existing has_one" do string = format_attr(crud_test_models(:AAAAA), :comrad) - expect(string).to eq('BBBBB') + expect(string).to eq("BBBBB") end - it 'formats existing has_many' do + it "formats existing has_many" do string = format_attr(crud_test_models(:CCCCC), :others) expect(string).to be_html_safe - expect(string).to eq('
  • AAAAA
  • BBBBB
') + expect(string).to eq("
  • AAAAA
  • BBBBB
") end end - describe '#column_type' do + describe "#column_type" do let(:model) { crud_test_models(:AAAAA) } - it 'recognizes types' do + it "recognizes types" do expect(column_type(model, :name)).to eq(:string) expect(column_type(model, :children)).to eq(:integer) expect(column_type(model, :companion_id)).to eq(:integer) @@ -195,47 +192,47 @@ def format_string_size(obj) # :nodoc: end end - describe '#format_type' do + describe "#format_type" do let(:model) { crud_test_models(:AAAAA) } - it 'formats integers' do + it "formats integers" do model.children = 10_000 - expect(format_type(model, :children)).to eq('10,000') + expect(format_type(model, :children)).to eq("10,000") end - unless ENV['NON_LOCALIZED'] # localization dependent tests - it 'formats floats' do - expect(format_type(model, :rating)).to eq('1.100') + unless ENV["NON_LOCALIZED"] # localization dependent tests + it "formats floats" do + expect(format_type(model, :rating)).to eq("1.100") end - it 'formata decimals' do - expect(format_type(model, :income)).to eq('10,000,000.1111') + it "formata decimals" do + expect(format_type(model, :income)).to eq("10,000,000.1111") end - it 'formats dates' do - expect(format_type(model, :birthdate)).to eq('1910-01-01') + it "formats dates" do + expect(format_type(model, :birthdate)).to eq("1910-01-01") end - it 'formats times' do - expect(format_type(model, :gets_up_at)).to eq('01:01') + it "formats times" do + expect(format_type(model, :gets_up_at)).to eq("01:01") end - it 'formats datetimes' do - expect(format_type(model, :last_seen)).to eq('2010-01-01 11:21') + it "formats datetimes" do + expect(format_type(model, :last_seen)).to eq("2010-01-01 11:21") end - it 'formats boolean false' do + it "formats boolean false" do model.human = false - expect(format_type(model, :human)).to eq('no') + expect(format_type(model, :human)).to eq("no") end - it 'formats boolean true' do + it "formats boolean true" do model.human = true - expect(format_type(model, :human)).to eq('yes') + expect(format_type(model, :human)).to eq("yes") end end - it 'formats texts' do + it "formats texts" do string = format_type(model, :remarks) expect(string).to be_html_safe expect(string).to eq( @@ -243,33 +240,32 @@ def format_string_size(obj) # :nodoc: ) end - it 'escapes texts' do - model.remarks = 'bla' + it "escapes texts" do + model.remarks = "bla" string = format_type(model, :remarks) expect(string).to be_html_safe - expect(string).to eq('

<unsecure>bla

') + expect(string).to eq("

<unsecure>bla

") end - it 'formats empty texts' do - model.remarks = ' ' + it "formats empty texts" do + model.remarks = " " string = format_type(model, :remarks) expect(string).to be_html_safe expect(string).to eq(UtilityHelper::EMPTY_STRING) end end - describe '#captionize' do - it 'handles symbols' do - expect(captionize(:camel_case)).to eq('Camel Case') + describe "#captionize" do + it "handles symbols" do + expect(captionize(:camel_case)).to eq("Camel Case") end - it 'renders all upper case' do - expect(captionize('all upper case')).to eq('All Upper Case') + it "renders all upper case" do + expect(captionize("all upper case")).to eq("All Upper Case") end - it 'renders human attribute name' do - expect(captionize(:gets_up_at, CrudTestModel)).to eq('Gets up at') + it "renders human attribute name" do + expect(captionize(:gets_up_at, CrudTestModel)).to eq("Gets up at") end end - end diff --git a/lib/generators/dry_crud/templates/spec/helpers/i18n_helper_spec.rb b/lib/generators/dry_crud/templates/spec/helpers/i18n_helper_spec.rb index 91af5a0..a664f97 100644 --- a/lib/generators/dry_crud/templates/spec/helpers/i18n_helper_spec.rb +++ b/lib/generators/dry_crud/templates/spec/helpers/i18n_helper_spec.rb @@ -1,101 +1,100 @@ -require 'rails_helper' +require "rails_helper" describe I18nHelper do - include CrudTestHelper - describe '#translate_inheritable' do + describe "#translate_inheritable" do before { @controller = CrudTestModelsController.new } before do I18n.backend.store_translations( I18n.locale, global: { - test_key: 'global' + test_key: "global" } ) end subject { ti(:test_key) } - it { is_expected.to eq('global') } + it { is_expected.to eq("global") } - context 'with list key' do + context "with list key" do before do I18n.backend.store_translations( I18n.locale, list: { global: { - test_key: 'list global' + test_key: "list global" } } ) end - it { is_expected.to eq('list global') } + it { is_expected.to eq("list global") } - context 'and list action key' do + context "and list action key" do before do I18n.backend.store_translations( I18n.locale, list: { index: { - test_key: 'list index' + test_key: "list index" } } ) end - it { is_expected.to eq('list index') } + it { is_expected.to eq("list index") } - context 'and crud global key' do + context "and crud global key" do before do I18n.backend.store_translations( I18n.locale, crud: { global: { - test_key: 'crud global' + test_key: "crud global" } } ) end - it { is_expected.to eq('crud global') } + it { is_expected.to eq("crud global") } - context 'and crud action key' do + context "and crud action key" do before do I18n.backend.store_translations( I18n.locale, crud: { index: { - test_key: 'crud index' + test_key: "crud index" } } ) end - it { is_expected.to eq('crud index') } + it { is_expected.to eq("crud index") } - context 'and controller global key' do + context "and controller global key" do before do I18n.backend.store_translations( I18n.locale, crud_test_models: { global: { - test_key: 'test global' + test_key: "test global" } } ) end - it { is_expected.to eq('test global') } + it { is_expected.to eq("test global") } - context 'and controller action key' do + context "and controller action key" do before do I18n.backend.store_translations( I18n.locale, crud_test_models: { index: { - test_key: 'test index' + test_key: "test index" } } ) end - it { is_expected.to eq('test index') } + it { is_expected.to eq("test index") } end end end @@ -104,7 +103,7 @@ end end - describe '#translate_association' do + describe "#translate_association" do let(:assoc) { CrudTestModel.reflect_on_association(:companion) } subject { ta(:test_key, assoc) } @@ -113,30 +112,30 @@ I18n.locale, global: { associations: { - test_key: 'global' + test_key: "global" } } ) end - it { is_expected.to eq('global') } + it { is_expected.to eq("global") } - context 'with model key' do + context "with model key" do before do I18n.backend.store_translations( I18n.locale, activerecord: { associations: { crud_test_model: { - test_key: 'model' + test_key: "model" } } } ) end - it { is_expected.to eq('model') } + it { is_expected.to eq("model") } - context 'and assoc key' do + context "and assoc key" do before do I18n.backend.store_translations( I18n.locale, @@ -145,7 +144,7 @@ models: { crud_test_model: { companion: { - test_key: 'companion' + test_key: "companion" } } } @@ -154,9 +153,9 @@ ) end - it { is_expected.to eq('companion') } - it 'uses global without assoc' do - expect(ta(:test_key)).to eq('global') + it { is_expected.to eq("companion") } + it "uses global without assoc" do + expect(ta(:test_key)).to eq("global") end end end diff --git a/lib/generators/dry_crud/templates/spec/helpers/table_helper_spec.rb b/lib/generators/dry_crud/templates/spec/helpers/table_helper_spec.rb index ef00b62..fa56b25 100644 --- a/lib/generators/dry_crud/templates/spec/helpers/table_helper_spec.rb +++ b/lib/generators/dry_crud/templates/spec/helpers/table_helper_spec.rb @@ -1,7 +1,6 @@ -require 'rails_helper' +require "rails_helper" describe TableHelper do - include FormatHelper include UtilityHelper include I18nHelper @@ -15,171 +14,171 @@ after(:all) { reset_db } - describe '#plain_table' do + describe "#plain_table" do subject { plain_table(%w[foo bar], :size) { |t| t.attrs :upcase } } - it 'contains attrs' do + it "contains attrs" do is_expected.to match(/Size<\/th>/) end - it 'contains block' do + it "contains block" do is_expected.to match(/Upcase<\/th>/) end end - describe '#plain_table_or_message' do - context 'with empty data' do + describe "#plain_table_or_message" do + context "with empty data" do subject { plain_table_or_message([]) } it { is_expected.to be_html_safe } - it 'handles empty data' do + it "handles empty data" do is_expected.to match(/div class=.table.>.+<\/div>/) end end - context 'with data' do + context "with data" do subject do plain_table_or_message(%w[foo bar], :size) { |t| t.attrs :upcase } end it { is_expected.to be_html_safe } - it 'renders table' do + it "renders table" do is_expected.to match(/^$/) end end end - describe '#list_table' do + describe "#list_table" do let(:entries) { CrudTestModel.all } - context 'default' do + context "default" do subject do with_test_routing { list_table } end - it 'has 7 rows' do + it "has 7 rows" do expect_pattern_count(REGEXP_ROWS, 7) end - it 'has 14 sortable headers' do + it "has 14 sortable headers" do expect_pattern_count(REGEXP_SORT_HEADERS, 14) end end - context 'with custom attributes' do + context "with custom attributes" do subject do with_test_routing { list_table(:name, :children, :companion_id) } end - it 'has 7 rows' do + it "has 7 rows" do expect_pattern_count(REGEXP_ROWS, 7) end - it 'has 3 sortable headers' do + it "has 3 sortable headers" do expect_pattern_count(REGEXP_SORT_HEADERS, 3) end end - context 'with custom block' do + context "with custom block" do subject do with_test_routing do list_table do |t| t.attrs :name, :children, :companion_id - t.col('head') { |e| tag.span(e.income.to_s) } + t.col("head") { |e| tag.span(e.income.to_s) } end end end - it 'has 7 rows' do + it "has 7 rows" do expect_pattern_count(REGEXP_ROWS, 7) end - it 'has 4 headers' do + it "has 4 headers" do expect_pattern_count(REGEXP_HEADERS, 4) end - it 'has 0 sortable headers' do + it "has 0 sortable headers" do expect_pattern_count(REGEXP_SORT_HEADERS, 0) end - it 'has 6 spans' do + it "has 6 spans" do expect_pattern_count(/.+?<\/span>/, 6) end end - context 'with custom attributes and block' do + context "with custom attributes and block" do subject do with_test_routing do list_table(:name, :children, :companion_id) do |t| - t.col('head') { |e| tag.span(e.income.to_s) } + t.col("head") { |e| tag.span(e.income.to_s) } end end end - it 'has 7 rows' do + it "has 7 rows" do expect_pattern_count(REGEXP_ROWS, 7) end - it 'has 4 headers' do + it "has 4 headers" do expect_pattern_count(REGEXP_HEADERS, 4) end - it 'has 3 sortable headers' do + it "has 3 sortable headers" do expect_pattern_count(REGEXP_SORT_HEADERS, 3) end - it 'has 6 spans' do + it "has 6 spans" do expect_pattern_count(/.+?<\/span>/, 6) end end - context 'with ascending sort params' do - let(:params) { { sort: 'children', sort_dir: 'asc' } } + context "with ascending sort params" do + let(:params) { { sort: "children", sort_dir: "asc" } } subject do with_test_routing { list_table } end - it 'has 13 sortable headers' do + it "has 13 sortable headers" do expect_pattern_count(REGEXP_SORT_HEADERS, 13) end - it 'has 1 ascending sort headers' do + it "has 1 ascending sort headers" do expect_pattern_count( /Children<\/a> ↓<\/th>/, 1 ) end end - context 'with descending sort params' do - let(:params) { { sort: 'children', sort_dir: 'desc' } } + context "with descending sort params" do + let(:params) { { sort: "children", sort_dir: "desc" } } subject do with_test_routing { list_table } end - it 'has 13 sortable headers' do + it "has 13 sortable headers" do expect_pattern_count(REGEXP_SORT_HEADERS, 13) end - it 'has 1 descending sort headers' do + it "has 1 descending sort headers" do expect_pattern_count( /Children<\/a> ↑<\/th>/, 1 ) end end - context 'with custom column sort params' do - let(:params) { { sort: 'chatty', sort_dir: 'asc' } } + context "with custom column sort params" do + let(:params) { { sort: "chatty", sort_dir: "asc" } } subject do with_test_routing { list_table(:name, :children, :chatty) } end - it 'has 2 sortable headers' do + it "has 2 sortable headers" do expect_pattern_count(REGEXP_SORT_HEADERS, 2) end - it 'has 1 ascending sort headers' do + it "has 1 ascending sort headers" do expect_pattern_count( /Chatty<\/a> ↓<\/th>/, 1 ) @@ -187,78 +186,78 @@ end end - describe '#crud_table' do + describe "#crud_table" do let(:entries) { CrudTestModel.all } - context 'default' do + context "default" do subject do with_test_routing { crud_table } end - it 'has 7 rows' do + it "has 7 rows" do expect_pattern_count(REGEXP_ROWS, 7) end - it 'has 14 sort headers' do + it "has 14 sort headers" do expect_pattern_count(REGEXP_SORT_HEADERS, 14) end - it 'has 12 action cells' do + it "has 12 action cells" do expect_pattern_count(REGEXP_ACTION_CELL, 12) end end - context 'with custom attrs' do + context "with custom attrs" do subject do with_test_routing { crud_table(:name, :children, :companion_id) } end - it 'has 3 sort headers' do + it "has 3 sort headers" do expect_pattern_count(REGEXP_SORT_HEADERS, 3) end end - context 'with custom block' do + context "with custom block" do subject do with_test_routing do crud_table do |t| t.attrs :name, :children, :companion_id - t.col('head') { |e| tag.span(e.income.to_s) } + t.col("head") { |e| tag.span(e.income.to_s) } end end end - it 'has 4 headers' do + it "has 4 headers" do expect_pattern_count(REGEXP_HEADERS, 6) end - it 'has 6 custom col spans' do + it "has 6 custom col spans" do expect_pattern_count(/.+?<\/span>/m, 6) end - it 'has 12 action cells' do + it "has 12 action cells" do expect_pattern_count(REGEXP_ACTION_CELL, 12) end end - context 'with custom attributes and block' do + context "with custom attributes and block" do subject do with_test_routing do crud_table(:name, :children, :companion_id) do |t| - t.col('head') { |e| tag.span(e.income.to_s) } + t.col("head") { |e| tag.span(e.income.to_s) } end end end - it 'has 3 sort headers' do + it "has 3 sort headers" do expect_pattern_count(REGEXP_SORT_HEADERS, 3) end - it 'has 6 custom col spans' do + it "has 6 custom col spans" do expect_pattern_count(/.+?<\/span>/m, 6) end - it 'has 12 action cells' do + it "has 12 action cells" do expect_pattern_count(REGEXP_ACTION_CELL, 12) end end @@ -267,5 +266,4 @@ def expect_pattern_count(pattern, count) expect(subject.scan(pattern).size).to eq(count) end - end diff --git a/lib/generators/dry_crud/templates/spec/helpers/utility_helper_spec.rb b/lib/generators/dry_crud/templates/spec/helpers/utility_helper_spec.rb index 1480961..564c755 100644 --- a/lib/generators/dry_crud/templates/spec/helpers/utility_helper_spec.rb +++ b/lib/generators/dry_crud/templates/spec/helpers/utility_helper_spec.rb @@ -1,7 +1,6 @@ -require 'rails_helper' +require "rails_helper" describe UtilityHelper do - include CrudTestHelper before(:all) do @@ -12,10 +11,10 @@ after(:all) { reset_db } - describe '#column_type' do + describe "#column_type" do let(:model) { crud_test_models(:AAAAA) } - it 'recognizes types' do + it "recognizes types" do expect(column_type(model, :name)).to eq(:string) expect(column_type(model, :children)).to eq(:integer) expect(column_type(model, :companion_id)).to eq(:integer) @@ -30,39 +29,38 @@ end end - describe '#content_tag_nested' do - - it 'escapes safe content' do + describe "#content_tag_nested" do + it "escapes safe content" do html = content_tag_nested(:div, %w[a b]) { |e| tag.span(e) } expect(html).to be_html_safe - expect(html).to eq('
ab
') + expect(html).to eq("
ab
") end - it 'escapes unsafe content' do + it "escapes unsafe content" do html = content_tag_nested(:div, %w[a b]) { |e| "<#{e}>" } - expect(html).to eq('
<a><b>
') + expect(html).to eq("
<a><b>
") end - it 'simplys join without block' do + it "simplys join without block" do html = content_tag_nested(:div, %w[a b]) - expect(html).to eq('
ab
') + expect(html).to eq("
ab
") end end - describe '#safe_join' do - it 'works as super without block' do - html = safe_join(['
', ''.html_safe]) - expect(html).to eq('<a>') + describe "#safe_join" do + it "works as super without block" do + html = safe_join([ "", "".html_safe ]) + expect(html).to eq("<a>") end - it 'collects contents for array' do + it "collects contents for array" do html = safe_join(%w[a b]) { |e| tag.span(e) } - expect(html).to eq('ab') + expect(html).to eq("ab") end end - describe '#default_crud_attrs' do - it 'do not contain id and password' do + describe "#default_crud_attrs" do + it "do not contain id and password" do expect(default_crud_attrs).to eq( %i[name email whatever children companion_id rating income birthdate gets_up_at last_seen human remarks @@ -70,5 +68,4 @@ ) end end - end diff --git a/lib/generators/dry_crud/templates/spec/support/crud_controller_examples.rb b/lib/generators/dry_crud/templates/spec/support/crud_controller_examples.rb index 8c9a2d2..9eaf63a 100644 --- a/lib/generators/dry_crud/templates/spec/support/crud_controller_examples.rb +++ b/lib/generators/dry_crud/templates/spec/support/crud_controller_examples.rb @@ -1,4 +1,4 @@ -require 'support/crud_controller_test_helper' +require "support/crud_controller_test_helper" RSpec.configure do |c| c.before failing: true do @@ -14,7 +14,7 @@ # them by passing a skip parameter with context arrays: # include_examples 'crud controller', # skip: [%w(index html sort) %w(destroy json)] -shared_examples 'crud controller' do |options| +shared_examples "crud controller" do |options| include CrudControllerTestHelper render_views @@ -40,53 +40,53 @@ end describe_action :get, :index, - unless: skip?(options, 'index') do - context '.html', + unless: skip?(options, "index") do + context ".html", format: :html, unless: skip?(options, %w[index html]) do - context 'plain', + context "plain", unless: skip?(options, %w[index html plain]), - combine: 'ihp' do + combine: "ihp" do it_is_expected_to_respond end - context 'search', + context "search", if: described_class.search_columns.present?, unless: skip?(options, %w[index html search]), - combine: 'ihse' do + combine: "ihse" do let(:params) { { q: search_value } } it_is_expected_to_respond - context 'entries' do + context "entries" do subject { entries } it { is_expected.to include(test_entry) } end end - context 'sort', + context "sort", unless: skip?(options, %w[index html sort]) do - context 'ascending', + context "ascending", unless: skip?(options, %w[index html sort ascending]), - combine: 'ihso' do - let(:params) { { sort: sort_column, sort_dir: 'asc' } } + combine: "ihso" do + let(:params) { { sort: sort_column, sort_dir: "asc" } } it_is_expected_to_respond - it 'has sorted entries' do + it "has sorted entries" do sorted = entries.sort_by(&sort_column.to_sym) expect(entries).to eq(sorted) end end - context 'descending', + context "descending", unless: skip?(options, %w[index html sort descending]), - combine: 'ihsd' do - let(:params) { { sort: sort_column, sort_dir: 'desc' } } + combine: "ihsd" do + let(:params) { { sort: sort_column, sort_dir: "desc" } } it_is_expected_to_respond - it 'has sorted entries' do + it "has sorted entries" do sorted = entries.sort_by(&sort_column.to_sym) expect(entries).to eq(sorted.reverse) end @@ -94,43 +94,43 @@ end end - context '.json', + context ".json", format: :json, unless: skip?(options, %w[index json]), - combine: 'ij' do + combine: "ij" do it_is_expected_to_respond - it { expect(response.body).to start_with('[{') } + it { expect(response.body).to start_with("[{") } end end describe_action :get, :show, id: true, - unless: skip?(options, 'show') do - context '.html', + unless: skip?(options, "show") do + context ".html", format: :html, unless: skip?(options, %w[show html]) do - context 'plain', + context "plain", unless: skip?(options, %w[show html plain]), - combine: 'sh' do + combine: "sh" do it_is_expected_to_respond end - context 'with non-existing id', + context "with non-existing id", unless: skip?(options, %w[show html with_non_existing_id]) do let(:params) { { id: 9999 } } - it 'raises RecordNotFound', perform_request: false do + it "raises RecordNotFound", perform_request: false do expect { perform_request } .to raise_error(ActiveRecord::RecordNotFound) end end end - context '.json', + context ".json", format: :json, unless: skip?(options, %w[show json]), - combine: 'sj' do + combine: "sj" do it_is_expected_to_respond it_is_expected_to_render_json end @@ -138,14 +138,14 @@ describe_action :get, :new, unless: skip?(options, %w[new]) do - context 'plain', + context "plain", unless: skip?(options, %w[new plain]), - combine: 'new' do + combine: "new" do it_is_expected_to_respond it_is_expected_to_persist_entry(persist: false) end - context 'with params', + context "with params", unless: skip?(options, %w[new with_params]) do let(:params) { { model_identifier => new_entry_attrs } } it_is_expected_to_set_attrs(:new) @@ -156,50 +156,50 @@ unless: skip?(options, %w[create]) do let(:params) { { model_identifier => new_entry_attrs } } - it 'adds entry to database', perform_request: false do + it "adds entry to database", perform_request: false do expect { perform_request }.to change { model_class.count }.by(1) end - context 'html', + context "html", format: :html, unless: skip?(options, %w[create html]) do it_is_expected_to_persist_entry # cannot combine this - context 'with valid params', + context "with valid params", unless: skip?(options, %w[create html valid]), - combine: 'chv' do + combine: "chv" do it_is_expected_to_redirect_to_show it_is_expected_to_set_attrs(:new) it_is_expected_to_have_flash(:notice) end - context 'with invalid params', + context "with invalid params", failing: true, unless: skip?(options, %w[create html invalid]), - combine: 'chi' do + combine: "chi" do it_is_expected_to_persist_entry(persist: false) it_is_expected_to_set_attrs(:new) it_is_expected_to_not_have_flash(:notice) end end - context 'json', + context "json", format: :json, unless: skip?(options, %w[create json]) do it_is_expected_to_persist_entry # cannot combine this - context 'with valid params', + context "with valid params", unless: skip?(options, %w[create json valid]), - combine: 'cjv' do + combine: "cjv" do it_is_expected_to_respond(201) it_is_expected_to_set_attrs(:new) it_is_expected_to_render_json end - context 'with invalid params', + context "with invalid params", failing: true, unless: skip?(options, %w[create json invalid]), - combine: 'cji' do + combine: "cji" do it_is_expected_to_respond(422) it_is_expected_to_set_attrs(:new) it_is_expected_to_render_json @@ -211,7 +211,7 @@ describe_action :get, :edit, id: true, unless: skip?(options, %w[edit]), - combine: 'edit' do + combine: "edit" do it_is_expected_to_respond end @@ -220,47 +220,47 @@ unless: skip?(options, %w[update]) do let(:params) { { model_identifier => edit_entry_attrs } } - it 'updates entry in database', perform_request: false do + it "updates entry in database", perform_request: false do expect { perform_request }.to change { model_class.count }.by(0) end - context '.html', + context ".html", format: :html, unless: skip?(options, %w[update html]) do - context 'with valid params', + context "with valid params", unless: skip?(options, %w[update html valid]), - combine: 'uhv' do + combine: "uhv" do it_is_expected_to_set_attrs(:edit) it_is_expected_to_redirect_to_show it_is_expected_to_persist_entry it_is_expected_to_have_flash(:notice) end - context 'with invalid params', + context "with invalid params", failing: true, unless: skip?(options, %w[update html invalid]), - combine: 'uhi' do + combine: "uhi" do it_is_expected_to_set_attrs(:edit) it_is_expected_to_not_have_flash(:notice) end end - context '.json', + context ".json", format: :json, unless: skip?(options, %w[update json]) do - context 'with valid params', + context "with valid params", unless: skip?(options, %w[update json valid]), - combine: 'ujv' do + combine: "ujv" do it_is_expected_to_respond(200) it_is_expected_to_set_attrs(:edit) it_is_expected_to_render_json it_is_expected_to_persist_entry end - context 'with invalid params', + context "with invalid params", failing: true, unless: skip?(options, %w[update json invalid]), - combine: 'uji' do + combine: "uji" do it_is_expected_to_respond(422) it_is_expected_to_set_attrs(:edit) it_is_expected_to_render_json @@ -271,33 +271,33 @@ describe_action :delete, :destroy, id: true, unless: skip?(options, %w[destroy]) do - it 'removes entry from database', perform_request: false do + it "removes entry from database", perform_request: false do expect { perform_request }.to change { model_class.count }.by(-1) end - context '.html', + context ".html", format: :html, unless: skip?(options, %w[destroy html]) do - context 'successfull', combine: 'dhs' do + context "successfull", combine: "dhs" do it_is_expected_to_redirect_to_index it_is_expected_to_have_flash(:notice) end - context 'with failure', failing: true, combine: 'dhf' do + context "with failure", failing: true, combine: "dhf" do it_is_expected_to_redirect_to_index it_is_expected_to_have_flash(:alert) end end - context '.json', + context ".json", format: :json, unless: skip?(options, %w[destroy json]) do - context 'successfull', combine: 'djs' do + context "successfull", combine: "djs" do it_is_expected_to_respond(204) it { expect(response.body).to be_blank } end - context 'with failure', failing: true, combine: 'djf' do + context "with failure", failing: true, combine: "djf" do it_is_expected_to_respond(422) it_is_expected_to_render_json end diff --git a/lib/generators/dry_crud/templates/spec/support/crud_controller_test_helper.rb b/lib/generators/dry_crud/templates/spec/support/crud_controller_test_helper.rb index da27b6a..52ebb59 100644 --- a/lib/generators/dry_crud/templates/spec/support/crud_controller_test_helper.rb +++ b/lib/generators/dry_crud/templates/spec/support/crud_controller_test_helper.rb @@ -56,7 +56,7 @@ def restore_request end def ivar(name) - controller.instance_variable_get("@#{name}") + controller.instance_variable_get(:"@#{name}") end # The params defining the nesting of the test entry. @@ -77,7 +77,6 @@ def scope_params # Helper methods to describe contexts. module ClassMethods - # Describe a certain action and provide some usefull metadata. # Tests whether this action is configured to be skipped. def describe_action(method, action, metadata = {}, &block) @@ -96,7 +95,7 @@ def skip?(options, *contexts) options ||= {} contexts = Array(contexts).flatten skips = Array(options[:skip]) - skips = [skips] if skips.blank? || !skips.first.is_a?(Array) + skips = [ skips ] if skips.blank? || !skips.first.is_a?(Array) skips.flatten.present? && skips.any? { |skip| skip == contexts.take(skip.size) } @@ -109,13 +108,13 @@ def it_is_expected_to_respond(status = 200) # Test that a json response is rendered. def it_is_expected_to_render_json - it { expect(response.body).to start_with('{') } + it { expect(response.body).to start_with("{") } end # Test that test_entry_attrs are set on entry. def it_is_expected_to_set_attrs(action = nil) - it 'sets params as entry attributes' do - attrs = send("#{action}_entry_attrs") + it "sets params as entry attributes" do + attrs = send(:"#{action}_entry_attrs") actual = {} attrs.each_key do |key| actual[key] = entry.attributes[key.to_s] @@ -127,7 +126,7 @@ def it_is_expected_to_set_attrs(action = nil) # Test that the response redirects to the index action. def it_is_expected_to_redirect_to_index it do - is_expected.to redirect_to scope_params.merge(action: 'index', + is_expected.to redirect_to scope_params.merge(action: "index", id: nil, returning: true) end @@ -136,7 +135,7 @@ def it_is_expected_to_redirect_to_index # Test that the response redirects to the show action of the current entry. def it_is_expected_to_redirect_to_show it do - is_expected.to redirect_to scope_params.merge(action: 'show', + is_expected.to redirect_to scope_params.merge(action: "show", id: entry.id) end end @@ -157,7 +156,7 @@ def it_is_expected_to_not_have_flash(type) # Test that the current entry is persistend and valid, or not. def it_is_expected_to_persist_entry(persist: true) - context 'entry' do + context "entry" do subject { entry } if persist @@ -169,5 +168,4 @@ def it_is_expected_to_persist_entry(persist: true) end end end - end diff --git a/lib/generators/dry_crud/templates/test/controllers/crud_test_models_controller_test.rb b/lib/generators/dry_crud/templates/test/controllers/crud_test_models_controller_test.rb index 37b984d..879e463 100644 --- a/lib/generators/dry_crud/templates/test/controllers/crud_test_models_controller_test.rb +++ b/lib/generators/dry_crud/templates/test/controllers/crud_test_models_controller_test.rb @@ -1,13 +1,12 @@ -require 'test_helper' -require 'support/crud_test_helper' -require 'support/crud_test_model' -require 'support/crud_controller_test_helper' +require "test_helper" +require "support/crud_test_helper" +require "support/crud_test_model" +require "support/crud_controller_test_helper" # Tests all actions of the CrudController based on a dummy model # (CrudTestModel). This is useful to test the general behavior # of CrudController. class CrudTestModelsControllerTest < ActionController::TestCase - include CrudControllerTestHelper include CrudTestHelper @@ -20,13 +19,13 @@ class CrudTestModelsControllerTest < ActionController::TestCase def test_setup assert_equal 6, CrudTestModel.count assert_equal CrudTestModelsController, @controller.class - assert_recognizes({ controller: 'crud_test_models', - action: 'index' }, - '/crud_test_models') - assert_recognizes({ controller: 'crud_test_models', - action: 'show', - id: '1' }, - '/crud_test_models/1') + assert_recognizes({ controller: "crud_test_models", + action: "index" }, + "/crud_test_models") + assert_recognizes({ controller: "crud_test_models", + action: "show", + id: "1" }, + "/crud_test_models/1") end def test_index @@ -39,14 +38,14 @@ def test_index def test_index_js get :index, params: test_params, xhr: true assert_response :success - assert_equal 'index js', @response.body + assert_equal "index js", @response.body assert entries.present? end def test_index_search super assert_equal 1, entries.size - assert_equal({ 'q' => 'AAAA' }, session[:list_params]['/crud_test_models']) + assert_equal({ "q" => "AAAA" }, session[:list_params]["/crud_test_models"]) end def test_index_with_custom_options @@ -58,65 +57,65 @@ def test_index_with_custom_options end def test_index_search_with_custom_options - get :index, params: { q: 'DDD', filter: true } + get :index, params: { q: "DDD", filter: true } assert_response :success assert entries.present? assert_equal 1, entries.size - assert_equal [CrudTestModel.find_by(name: 'BBBBB')], entries - assert_equal({ 'q' => 'DDD' }, session[:list_params]['/crud_test_models']) + assert_equal [ CrudTestModel.find_by(name: "BBBBB") ], entries + assert_equal({ "q" => "DDD" }, session[:list_params]["/crud_test_models"]) end def test_sort_given_column - get :index, params: { sort: 'children', sort_dir: 'asc' } + get :index, params: { sort: "children", sort_dir: "asc" } assert_response :success assert entries.present? assert_equal 6, entries.size assert_equal CrudTestModel.all.sort_by(&:children), entries - assert_equal({ 'sort' => 'children', 'sort_dir' => 'asc' }, - session[:list_params]['/crud_test_models']) + assert_equal({ "sort" => "children", "sort_dir" => "asc" }, + session[:list_params]["/crud_test_models"]) end def test_sort_virtual_column - get :index, params: { sort: 'chatty', sort_dir: 'desc' } + get :index, params: { sort: "chatty", sort_dir: "desc" } assert_response :success assert entries.present? assert_equal 6, entries.size - assert_equal({ 'sort' => 'chatty', 'sort_dir' => 'desc' }, - session[:list_params]['/crud_test_models']) + assert_equal({ "sort" => "chatty", "sort_dir" => "desc" }, + session[:list_params]["/crud_test_models"]) # sort order is ambiguous, use index names = entries.map(&:name) - assert names.index('BBBBB') < names.index('AAAAA') - assert names.index('BBBBB') < names.index('DDDDD') - assert names.index('EEEEE') < names.index('AAAAA') - assert names.index('EEEEE') < names.index('DDDDD') - assert names.index('AAAAA') < names.index('CCCCC') - assert names.index('DDDDD') < names.index('CCCCC') + assert names.index("BBBBB") < names.index("AAAAA") + assert names.index("BBBBB") < names.index("DDDDD") + assert names.index("EEEEE") < names.index("AAAAA") + assert names.index("EEEEE") < names.index("DDDDD") + assert names.index("AAAAA") < names.index("CCCCC") + assert names.index("DDDDD") < names.index("CCCCC") end def test_sort_with_search - get :index, params: { q: 'DDD', sort: 'chatty', sort_dir: 'asc' } + get :index, params: { q: "DDD", sort: "chatty", sort_dir: "asc" } assert_response :success assert entries.present? assert_equal 3, entries.size assert_equal %w[CCCCC DDDDD BBBBB], entries.map(&:name) - assert_equal({ 'sort' => 'chatty', 'sort_dir' => 'asc', 'q' => 'DDD' }, - session[:list_params]['/crud_test_models']) + assert_equal({ "sort" => "chatty", "sort_dir" => "asc", "q" => "DDD" }, + session[:list_params]["/crud_test_models"]) end def test_index_returning session[:list_params] = {} - session[:list_params]['/crud_test_models'] = { 'q' => 'DDD', - 'sort' => 'chatty', - 'sort_dir' => 'desc' } + session[:list_params]["/crud_test_models"] = { "q" => "DDD", + "sort" => "chatty", + "sort_dir" => "desc" } get :index, params: { returning: true } assert_response :success assert entries.present? assert_equal 3, entries.size assert_equal %w[BBBBB DDDDD CCCCC], entries.map(&:name) - assert_equal 'DDD', @controller.params[:q] - assert_equal 'chatty', @controller.params[:sort] - assert_equal 'desc', @controller.params[:sort_dir] + assert_equal "DDD", @controller.params[:q] + assert_equal "chatty", @controller.params[:sort] + assert_equal "desc", @controller.params[:sort_dir] end def test_new @@ -128,7 +127,7 @@ def test_new def test_show_with_custom get :show, params: test_params(id: crud_test_models(:BBBBB).id) assert_response :success - assert_equal 'custom html', @response.body + assert_equal "custom html", @response.body end def test_create @@ -147,8 +146,8 @@ def test_edit def test_update super - assert_equal I18n.t('crud.update.flash.success', - model: 'Crud Test Model foo'), + assert_equal I18n.t("crud.update.flash.success", + model: "Crud Test Model foo"), flash[:notice] assert flash[:alert].blank? assert_equal %i[before_update before_save after_save after_update], @@ -159,42 +158,42 @@ def test_destroy super assert_equal %i[before_destroy after_destroy], @controller.called_callbacks - assert_equal I18n.t('crud.destroy.flash.success', - model: 'Crud Test Model AAAAA'), + assert_equal I18n.t("crud.destroy.flash.success", + model: "Crud Test Model AAAAA"), flash[:notice] end def test_create_with_before_callback - assert_no_difference('CrudTestModel.count') do + assert_no_difference("CrudTestModel.count") do post :create, - params: { crud_test_model: { name: 'illegal', children: 2 } } + params: { crud_test_model: { name: "illegal", children: 2 } } end assert_response :success assert entry.new_record? assert flash[:alert].present? - assert_equal 'illegal', entry.name + assert_equal "illegal", entry.name assert_equal %i[before_render_new before_render_form], @controller.called_callbacks end def test_create_with_before_callback_redirect @controller.should_redirect = true - assert_no_difference('CrudTestModel.count') do + assert_no_difference("CrudTestModel.count") do post :create, - params: { crud_test_model: { name: 'illegal', children: 2 } } + params: { crud_test_model: { name: "illegal", children: 2 } } end - assert_redirected_to action: 'index' + assert_redirected_to action: "index" assert_nil @controller.called_callbacks end def test_new_with_before_render_callback_redirect_does_not_set_companions @controller.should_redirect = true get :new - assert_redirected_to action: 'index' + assert_redirected_to action: "index" end def test_create_with_failure - assert_no_difference('CrudTestModel.count') do + assert_no_difference("CrudTestModel.count") do post :create, params: { crud_test_model: { children: 2 } } end assert_response :success @@ -208,8 +207,8 @@ def test_create_with_failure end def test_create_with_failure_json - assert_no_difference('CrudTestModel.count') do - post :create, params: { crud_test_model: { children: 2 }, format: 'json' } + assert_no_difference("CrudTestModel.count") do + post :create, params: { crud_test_model: { children: 2 }, format: "json" } end assert_response :unprocessable_entity assert entry.new_record? @@ -234,7 +233,7 @@ def test_update_with_failure_does_not_update_many_relations id: test_entry.id, crud_test_model: { rating: 20, - other_ids: [OtherCrudTestModel.first.id] + other_ids: [ OtherCrudTestModel.first.id ] } } assert_response :success @@ -252,7 +251,7 @@ def test_update_with_failure_json put :update, params: { id: test_entry.id, crud_test_model: { rating: 20 }, - format: 'json' } + format: "json" } assert_response :unprocessable_entity assert entry.changed? assert flash[:notice].blank? @@ -262,7 +261,7 @@ def test_update_with_failure_json def test_destroy_failure assert_no_difference("#{model_class.name}.count") do - @request.env['HTTP_REFERER'] = + @request.env["HTTP_REFERER"] = crud_test_model_url(crud_test_models(:BBBBB)) delete :destroy, params: test_params(id: crud_test_models(:BBBBB).id) end @@ -274,7 +273,7 @@ def test_destroy_failure def test_destroy_failure_callback e = crud_test_models(:AAAAA) # rubocop:disable Rails/SkipsModelValidations - e.update_attribute(:name, 'illegal') + e.update_attribute(:name, "illegal") # rubocop:enable Rails/SkipsModelValidations assert_no_difference("#{model_class.name}.count") do delete :destroy, params: test_params(id: e.id) @@ -287,15 +286,15 @@ def test_destroy_failure_callback def test_destroy_failure_json assert_no_difference("#{model_class.name}.count") do delete :destroy, params: test_params(id: crud_test_models(:BBBBB).id, - format: 'json') + format: "json") end assert_response :unprocessable_entity assert flash[:notice].blank? end def test_models_label - assert_equal 'Crud Test Models', @controller.models_label - assert_equal 'Crud Test Model', @controller.models_label(plural: false) + assert_equal "Crud Test Models", @controller.models_label + assert_equal "Crud Test Model", @controller.models_label(plural: false) end private @@ -305,24 +304,23 @@ def test_entry end def new_entry_attrs - { name: 'foo', + { name: "foo", children: 42, companion_id: 3, rating: 8.5, income: 2.42, - birthdate: '31-12-1999'.to_date, + birthdate: "31-12-1999".to_date, human: true, remarks: "some custom\n\tremarks" } end def edit_entry_attrs - { name: 'foo', + { name: "foo", children: 42, rating: 8.5, income: 2.42, - birthdate: '31-12-1999'.to_date, + birthdate: "31-12-1999".to_date, human: true, remarks: "some custom\n\tremarks" } end - end diff --git a/lib/generators/dry_crud/templates/test/helpers/custom_assertions_test.rb b/lib/generators/dry_crud/templates/test/helpers/custom_assertions_test.rb index e049805..f4db7da 100644 --- a/lib/generators/dry_crud/templates/test/helpers/custom_assertions_test.rb +++ b/lib/generators/dry_crud/templates/test/helpers/custom_assertions_test.rb @@ -1,72 +1,71 @@ -require 'test_helper' -require 'support/custom_assertions' -require 'support/crud_test_helper' -require 'support/crud_test_model' +require "test_helper" +require "support/custom_assertions" +require "support/crud_test_helper" +require "support/crud_test_model" # Test CustomAssertions class CustomAssertionsTest < ActiveSupport::TestCase - include CustomAssertions include CrudTestHelper setup :reset_db, :setup_db, :create_test_data teardown :reset_db - test 'assert count succeeds if count matches' do + test "assert count succeeds if count matches" do assert_nothing_raised do - assert_count 3, 'ba', 'barbabapa' + assert_count 3, "ba", "barbabapa" end end - test 'assert count succeeds if count is zero' do + test "assert count succeeds if count is zero" do assert_nothing_raised do - assert_count 0, 'bo', 'barbabapa' + assert_count 0, "bo", "barbabapa" end end - test 'assert count fails if count does not match' do + test "assert count fails if count does not match" do assert_raise(Minitest::Assertion) do - assert_count 2, 'ba', 'barbabapa' + assert_count 2, "ba", "barbabapa" end end - test 'assert valid record succeeds' do + test "assert valid record succeeds" do assert_nothing_raised do - assert_valid crud_test_models('AAAAA') + assert_valid crud_test_models("AAAAA") end end - test 'assert valid record fails for invalid' do + test "assert valid record fails for invalid" do assert_raise(Minitest::Assertion) do assert_valid invalid_record end end - test 'assert not valid succeeds if record invalid' do + test "assert not valid succeeds if record invalid" do assert_nothing_raised do assert_not_valid invalid_record end end - test 'assert not valid succeds if record invalid and invalid attrs given' do + test "assert not valid succeds if record invalid and invalid attrs given" do assert_nothing_raised do assert_not_valid invalid_record, :name, :rating end end - test 'assert not valid fails if record valid' do + test "assert not valid fails if record valid" do assert_raise(Minitest::Assertion) do - assert_not_valid crud_test_models('AAAAA') + assert_not_valid crud_test_models("AAAAA") end end - test 'assert not valid fails if record invalid and valid attrs given' do + test "assert not valid fails if record invalid and valid attrs given" do assert_raise(Minitest::Assertion) do assert_not_valid invalid_record, :name, :rating, :children end end - test 'assert not valid fails if not all invalid attrs given' do + test "assert not valid fails if not all invalid attrs given" do assert_raise(Minitest::Assertion) do assert_not_valid invalid_record, :name end @@ -75,10 +74,9 @@ class CustomAssertionsTest < ActiveSupport::TestCase private def invalid_record - m = crud_test_models('AAAAA') + m = crud_test_models("AAAAA") m.name = nil m.rating = 42 m end - end diff --git a/lib/generators/dry_crud/templates/test/helpers/dry_crud/form/builder_test.rb b/lib/generators/dry_crud/templates/test/helpers/dry_crud/form/builder_test.rb index 852f52e..3458016 100644 --- a/lib/generators/dry_crud/templates/test/helpers/dry_crud/form/builder_test.rb +++ b/lib/generators/dry_crud/templates/test/helpers/dry_crud/form/builder_test.rb @@ -1,5 +1,5 @@ -require 'test_helper' -require 'support/crud_test_model' +require "test_helper" +require "support/crud_test_model" module DryCrud module Form @@ -22,226 +22,226 @@ def create_form @form = DryCrud::Form::Builder.new(:entry, @entry, self, {}) end - test 'input_field dispatches string attr to string_field' do + test "input_field dispatches string attr to string_field" do assert_equal form.with_addon( form.string_field(:name, - required: 'required'), - '*' + required: "required"), + "*" ), form.input_field(:name) assert form.string_field(:name).html_safe? end - test 'input_field dispatches password attr to password_field' do + test "input_field dispatches password attr to password_field" do assert_equal form.password_field(:password), form.input_field(:password) assert form.password_field(:name).html_safe? end - test 'input_field dispatches email attr to email_field' do + test "input_field dispatches email attr to email_field" do assert_equal form.email_field(:email), form.input_field(:email) assert form.email_field(:name).html_safe? end - test 'input_field dispatches text attr to text_area' do + test "input_field dispatches text attr to text_area" do assert_equal form.text_area(:remarks), form.input_field(:remarks) assert form.text_area(:remarks).html_safe? end - test 'input_field dispatches integer attr to integer_field' do + test "input_field dispatches integer attr to integer_field" do assert_equal form.integer_field(:children), form.input_field(:children) assert form.integer_field(:children).html_safe? end - test 'input_field dispatches boolean attr to boolean_field' do + test "input_field dispatches boolean attr to boolean_field" do assert_equal form.boolean_field(:human), form.input_field(:human) assert form.boolean_field(:human).html_safe? end - test 'input_field dispatches date attr to date_field' do + test "input_field dispatches date attr to date_field" do assert_equal form.date_field(:birthdate), form.input_field(:birthdate) assert form.date_field(:birthdate).html_safe? end - test 'input_field dispatches belongs_to attr to select field' do + test "input_field dispatches belongs_to attr to select field" do assert_equal form.belongs_to_field(:companion_id), form.input_field(:companion_id) assert form.belongs_to_field(:companion_id).html_safe? end - test 'input_field dispatches has_and_belongs_to_many attr to ' \ - 'select field' do + test "input_field dispatches has_and_belongs_to_many attr to " \ + "select field" do assert_equal form.has_many_field(:other_ids), form.input_field(:other_ids) assert form.has_many_field(:other_ids).html_safe? end - test 'input_field dispatches has_many attr to select field' do + test "input_field dispatches has_many attr to select field" do assert_equal form.has_many_field(:more_ids), form.input_field(:more_ids) assert form.has_many_field(:more_ids).html_safe? end - test 'input_fields concats multiple fields' do + test "input_fields concats multiple fields" do result = form.labeled_input_fields(:name, :remarks, :children) assert result.html_safe? - assert result.include?(form.input_field(:name, required: 'required')) + assert result.include?(form.input_field(:name, required: "required")) assert result.include?(form.input_field(:remarks)) assert result.include?(form.input_field(:children)) end - test 'labeld_input_field adds required mark' do + test "labeld_input_field adds required mark" do result = form.labeled_input_field(:name) - assert result.include?('input-group-text') + assert result.include?("input-group-text") result = form.labeled_input_field(:remarks) - assert_not result.include?('input-group-text') + assert_not result.include?("input-group-text") end - test 'labeld_input_field adds help text' do - result = form.labeled_input_field(:name, help: 'Some Help') - assert result.include?(form.help_block('Some Help')) - assert result.include?('input-group-text') + test "labeld_input_field adds help text" do + result = form.labeled_input_field(:name, help: "Some Help") + assert result.include?(form.help_block("Some Help")) + assert result.include?("input-group-text") end - test 'belongs_to_field has all options by default' do + test "belongs_to_field has all options by default" do f = form.belongs_to_field(:companion_id) - assert_equal 7, f.scan('').size + assert_equal 7, f.scan("").size end - test 'belongs_to_field with :list option' do + test "belongs_to_field with :list option" do list = CrudTestModel.all f = form.belongs_to_field(:companion_id, - list: [list.first, list.second]) - assert_equal 3, f.scan('').size + list: [ list.first, list.second ]) + assert_equal 3, f.scan("").size end - test 'belongs_to_field with instance variable' do + test "belongs_to_field with instance variable" do list = CrudTestModel.all - @companions = [list.first, list.second] + @companions = [ list.first, list.second ] f = form.belongs_to_field(:companion_id) - assert_equal 3, f.scan('').size + assert_equal 3, f.scan("").size end - test 'belongs_to_field with empty list' do + test "belongs_to_field with empty list" do @companions = [] f = form.belongs_to_field(:companion_id) - assert_match t('global.associations.none_available'), f - assert_equal 0, f.scan('').size + assert_match t("global.associations.none_available"), f + assert_equal 0, f.scan("").size end - test 'has_and_belongs_to_many_field has all options by default' do + test "has_and_belongs_to_many_field has all options by default" do f = form.has_many_field(:other_ids) - assert_equal 6, f.scan('').size + assert_equal 6, f.scan("").size end - test 'has_and_belongs_to_many_field with :list option' do + test "has_and_belongs_to_many_field with :list option" do list = OtherCrudTestModel.all - f = form.has_many_field(:other_ids, list: [list.first, list.second]) - assert_equal 2, f.scan('').size + f = form.has_many_field(:other_ids, list: [ list.first, list.second ]) + assert_equal 2, f.scan("").size end - test 'has_and_belongs_to_many_field with instance variable' do + test "has_and_belongs_to_many_field with instance variable" do list = OtherCrudTestModel.all - @others = [list.first, list.second] + @others = [ list.first, list.second ] f = form.has_many_field(:other_ids) - assert_equal 2, f.scan('').size + assert_equal 2, f.scan("").size end - test 'has_and_belongs_to_many_field with empty list' do + test "has_and_belongs_to_many_field with empty list" do @others = [] f = form.has_many_field(:other_ids) - assert_match t('global.associations.none_available'), f - assert_equal 0, f.scan('').size + assert_match t("global.associations.none_available"), f + assert_equal 0, f.scan("").size end - test 'has_many_field has all options by default' do + test "has_many_field has all options by default" do f = form.has_many_field(:more_ids) - assert_equal 6, f.scan('').size + assert_equal 6, f.scan("").size end - test 'has_many_field with :list option' do + test "has_many_field with :list option" do list = OtherCrudTestModel.all - f = form.has_many_field(:more_ids, list: [list.first, list.second]) - assert_equal 2, f.scan('').size + f = form.has_many_field(:more_ids, list: [ list.first, list.second ]) + assert_equal 2, f.scan("").size end - test 'has_many_field with instance variable' do + test "has_many_field with instance variable" do list = OtherCrudTestModel.all - @mores = [list.first, list.second] + @mores = [ list.first, list.second ] f = form.has_many_field(:more_ids) - assert_equal 2, f.scan('').size + assert_equal 2, f.scan("").size end - test 'has_many_field with empty list' do + test "has_many_field with empty list" do @mores = [] f = form.has_many_field(:more_ids) - assert_match t('global.associations.none_available'), f - assert_equal 0, f.scan('').size + assert_match t("global.associations.none_available"), f + assert_equal 0, f.scan("").size end - test 'string_field sets maxlength attribute if limit' do + test "string_field sets maxlength attribute if limit" do assert_match(/maxlength="50"/, form.string_field(:name)) end - test 'label creates captionized label' do + test "label creates captionized label" do assert_match(/label [^>]*for.+Gugus dada/, form.label(:gugus_dada)) assert form.label(:gugus_dada).html_safe? end - test 'classic label still works' do - assert_match(/label [^>]*for.+hoho/, form.label(:gugus_dada, 'hoho')) - assert form.label(:gugus_dada, 'hoho').html_safe? + test "classic label still works" do + assert_match(/label [^>]*for.+hoho/, form.label(:gugus_dada, "hoho")) + assert form.label(:gugus_dada, "hoho").html_safe? end - test 'labeled_text_field create label' do + test "labeled_text_field create label" do assert_match(/label [^>]*for.+input/m, form.labeled_string_field(:name)) assert form.labeled_string_field(:name).html_safe? end - test 'labeled field creates label' do - result = form.labeled('gugus', + test "labeled field creates label" do + result = form.labeled("gugus", "".html_safe) assert result.html_safe? assert_match(/label [^>]*for.+".html_safe end assert result.html_safe? assert_match(/label [^>]*for.+".html_safe, - caption: 'Caption') + caption: "Caption") assert result.html_safe? assert_match(/label [^>]*for.+>Caption<\/label>.*".html_safe end assert result.html_safe? assert_match(/label [^>]*for.+>Caption<\/label>.*Upcase', col.html_header - assert_equal 'FOO', col.content('foo') - assert_equal 'FOO', col.html_cell('foo') + assert_equal "Upcase", col.html_header + assert_equal "FOO", col.content("foo") + assert_equal "FOO", col.html_cell("foo") end - test 'attr col content with custom format_size method' do + test "attr col content with custom format_size method" do table.attrs :size col = table.cols.first - assert_equal '4 chars', col.content('abcd') + assert_equal "4 chars", col.content("abcd") end - test 'two x two table' do + test "two x two table" do dom = <<-FIN @@ -72,14 +72,14 @@ def format_size(obj)
FIN - dom.gsub!(/[\n\t]/, '').gsub!(/\s{2,}/, '') + dom.gsub!(/[\n\t]/, "").gsub!(/\s{2,}/, "") table.attrs :upcase, :size assert_dom_equal dom, table.to_html end - test 'table with before and after cells' do + test "table with before and after cells" do dom = <<-FIN @@ -105,16 +105,16 @@ def format_size(obj)
FIN - dom.gsub!(/[\n\t]/, '').gsub!(/\s{2,}/, '') + dom.gsub!(/[\n\t]/, "").gsub!(/\s{2,}/, "") - table.col('head', class: 'left') { |e| link_to e, '/' } + table.col("head", class: "left") { |e| link_to e, "/" } table.attrs :upcase, :size table.col { |e| "Never #{e}" } assert_dom_equal dom, table.to_html end - test 'empty entries collection renders empty table' do + test "empty entries collection renders empty table" do dom = <<-FIN @@ -129,10 +129,10 @@ def format_size(obj)
FIN - dom.gsub!(/[\n\t]/, '').gsub!(/\s{2,}/, '') + dom.gsub!(/[\n\t]/, "").gsub!(/\s{2,}/, "") table = DryCrud::Table::Builder.new([], self) - table.col('head', class: 'left') { |e| link_to e, '/' } + table.col("head", class: "left") { |e| link_to e, "/" } table.attrs :upcase, :size table.col { |e| "Never #{e}" } diff --git a/lib/generators/dry_crud/templates/test/helpers/form_helper_test.rb b/lib/generators/dry_crud/templates/test/helpers/form_helper_test.rb index 1842133..51cb783 100644 --- a/lib/generators/dry_crud/templates/test/helpers/form_helper_test.rb +++ b/lib/generators/dry_crud/templates/test/helpers/form_helper_test.rb @@ -1,10 +1,9 @@ -require 'test_helper' -require 'support/crud_test_model' -require 'support/crud_test_helper' +require "test_helper" +require "support/crud_test_model" +require "support/crud_test_helper" # Test FormHelper class FormHelperTest < ActionView::TestCase - include UtilityHelper include FormatHelper include I18nHelper @@ -13,11 +12,11 @@ class FormHelperTest < ActionView::TestCase setup :reset_db, :setup_db, :create_test_data teardown :reset_db - test 'plain form for existing entry' do - e = crud_test_models('AAAAA') + test "plain form for existing entry" do + e = crud_test_models("AAAAA") f = with_test_routing do capture do - plain_form(e, html: { class: 'special' }) do |form| + plain_form(e, html: { class: "special" }) do |form| form.labeled_input_fields :name, :birthdate end end @@ -34,14 +33,14 @@ class FormHelperTest < ActionView::TestCase .*?name="crud_test_model\[name\]"/x, f) end - test 'standard form' do - e = crud_test_models('AAAAA') + test "standard form" do + e = crud_test_models("AAAAA") f = with_test_routing do capture do standard_form(e, :name, :children, :birthdate, :human, - cancel_url: '/somewhere', - html: { class: 'special' }) + cancel_url: "/somewhere", + html: { class: "special" }) end end @@ -69,8 +68,8 @@ class FormHelperTest < ActionView::TestCase <\/a>/x, f) end - test 'standard form with errors' do - e = crud_test_models('AAAAA') + test "standard form with errors" do + e = crud_test_models("AAAAA") e.name = nil assert_not e.valid? @@ -96,7 +95,7 @@ class FormHelperTest < ActionView::TestCase .*?name="crud_test_model\[birthdate\]"/x, f) end - test 'crud form' do + test "crud form" do f = with_test_routing do capture { crud_form } end @@ -129,5 +128,4 @@ class FormHelperTest < ActionView::TestCase def entry @entry ||= CrudTestModel.first end - end diff --git a/lib/generators/dry_crud/templates/test/helpers/format_helper_test.rb b/lib/generators/dry_crud/templates/test/helpers/format_helper_test.rb index 017ec07..f258501 100644 --- a/lib/generators/dry_crud/templates/test/helpers/format_helper_test.rb +++ b/lib/generators/dry_crud/templates/test/helpers/format_helper_test.rb @@ -1,9 +1,8 @@ -require 'test_helper' -require 'support/crud_test_model' +require "test_helper" +require "support/crud_test_model" # Test FormatHelper class FormatHelperTest < ActionView::TestCase - include UtilityHelper include I18nHelper include CrudTestHelper @@ -19,167 +18,166 @@ def format_string_size(obj) "#{f(obj.size)} chars" end - test 'labeled text as block' do - result = labeled('label') { 'value' } + test "labeled text as block" do + result = labeled("label") { "value" } assert result.html_safe? - assert_dom_equal '
label
' \ + assert_dom_equal "
label
" \ "
value
", result.squish end - test 'labeled text empty' do - result = labeled('label', '') + test "labeled text empty" do + result = labeled("label", "") assert result.html_safe? - assert_dom_equal '
label
' \ + assert_dom_equal "
label
" \ "
#{EMPTY_STRING}
", result.squish end - test 'labeled text as content' do - result = labeled('label', 'value ') + test "labeled text as content" do + result = labeled("label", "value ") assert result.html_safe? - assert_dom_equal '
label
' \ + assert_dom_equal "
label
" \ "
value <unsafe>
", result.squish end - test 'labeled attr' do - result = labeled_attr('foo', :size) + test "labeled attr" do + result = labeled_attr("foo", :size) assert result.html_safe? - assert_dom_equal '
Size
' \ + assert_dom_equal "
Size
" \ "
3 chars
", result.squish end - test 'format nil' do + test "format nil" do assert EMPTY_STRING.html_safe? assert_equal EMPTY_STRING, f(nil) end - test 'format Strings' do - assert_equal 'blah blah', f('blah blah') - assert_equal '', f('') - assert_not f('').html_safe? + test "format Strings" do + assert_equal "blah blah", f("blah blah") + assert_equal "", f("") + assert_not f("").html_safe? end - unless ENV['NON_LOCALIZED'] # localization dependent tests - test 'format Floats' do - assert_equal '1.000', f(1.0) - assert_equal '1.200', f(1.2) - assert_equal '3.142', f(3.14159) + unless ENV["NON_LOCALIZED"] # localization dependent tests + test "format Floats" do + assert_equal "1.000", f(1.0) + assert_equal "1.200", f(1.2) + assert_equal "3.142", f(3.14159) end - test 'format Booleans' do - assert_equal 'yes', f(true) - assert_equal 'no', f(false) + test "format Booleans" do + assert_equal "yes", f(true) + assert_equal "no", f(false) end - test 'format attr with fallthrough to f' do - assert_equal '12.234', format_attr('12.23424', :to_f) + test "format attr with fallthrough to f" do + assert_equal "12.234", format_attr("12.23424", :to_f) end end - test 'format attr with custom format_string_size method' do - assert_equal '4 chars', format_attr('abcd', :size) + test "format attr with custom format_string_size method" do + assert_equal "4 chars", format_attr("abcd", :size) end - test 'format attr with custom format_size method' do - assert_equal '2 items', format_attr([1, 2], :size) + test "format attr with custom format_size method" do + assert_equal "2 items", format_attr([ 1, 2 ], :size) end - test 'format integer column' do + test "format integer column" do m = crud_test_models(:AAAAA) - assert_equal '9', format_type(m, :children) + assert_equal "9", format_type(m, :children) m.children = 10_000 - assert_equal '10,000', format_type(m, :children) + assert_equal "10,000", format_type(m, :children) end - unless ENV['NON_LOCALIZED'] # localization dependent tests - test 'format float column' do + unless ENV["NON_LOCALIZED"] # localization dependent tests + test "format float column" do m = crud_test_models(:AAAAA) - assert_equal '1.100', format_type(m, :rating) + assert_equal "1.100", format_type(m, :rating) m.rating = 3.145001 # you never know with these floats.. - assert_equal '3.145', format_type(m, :rating) + assert_equal "3.145", format_type(m, :rating) end - test 'format decimal column' do + test "format decimal column" do m = crud_test_models(:AAAAA) - assert_equal '10,000,000.1111', format_type(m, :income) + assert_equal "10,000,000.1111", format_type(m, :income) end - test 'format date column' do + test "format date column" do m = crud_test_models(:AAAAA) - assert_equal '1910-01-01', format_type(m, :birthdate) + assert_equal "1910-01-01", format_type(m, :birthdate) end - test 'format datetime column' do + test "format datetime column" do m = crud_test_models(:AAAAA) - assert_equal '2010-01-01 11:21', format_type(m, :last_seen) + assert_equal "2010-01-01 11:21", format_type(m, :last_seen) end end - test 'format time column' do + test "format time column" do m = crud_test_models(:AAAAA) - assert_equal '01:01', format_type(m, :gets_up_at) + assert_equal "01:01", format_type(m, :gets_up_at) end - test 'format text column' do + test "format text column" do m = crud_test_models(:AAAAA) assert_equal "

AAAAA BBBBB CCCCC\n
AAAAA BBBBB CCCCC\n

", format_type(m, :remarks) assert format_type(m, :remarks).html_safe? end - test 'format boolean false column' do + test "format boolean false column" do m = crud_test_models(:AAAAA) m.human = false - assert_equal 'no', format_type(m, :human) + assert_equal "no", format_type(m, :human) end - test 'format boolean true column' do + test "format boolean true column" do m = crud_test_models(:AAAAA) m.human = true - assert_equal 'yes', format_type(m, :human) + assert_equal "yes", format_type(m, :human) end - test 'format belongs to column without content' do + test "format belongs to column without content" do m = crud_test_models(:AAAAA) - assert_equal t('global.associations.no_entry'), + assert_equal t("global.associations.no_entry"), format_attr(m, :companion) end - test 'format belongs to column with content' do + test "format belongs to column with content" do m = crud_test_models(:BBBBB) - assert_equal 'AAAAA', format_attr(m, :companion) + assert_equal "AAAAA", format_attr(m, :companion) end - test 'format has one without content' do + test "format has one without content" do m = crud_test_models(:FFFFF) - assert_equal t('global.associations.no_entry'), + assert_equal t("global.associations.no_entry"), format_attr(m, :comrad) end - test 'format has one with content' do + test "format has one with content" do m = crud_test_models(:AAAAA) - assert_equal 'BBBBB', format_attr(m, :comrad) + assert_equal "BBBBB", format_attr(m, :comrad) end - test 'format has_many column with content' do + test "format has_many column with content" do m = crud_test_models(:CCCCC) - assert_equal '
  • AAAAA
  • BBBBB
', + assert_equal "
  • AAAAA
  • BBBBB
", format_attr(m, :others) end - test 'captionize' do - assert_equal 'Camel Case', captionize(:camel_case) - assert_equal 'All Upper Case', captionize('all upper case') - assert_equal 'With Object', captionize('With object', Object.new) - assert_not captionize('bad ').html_safe? + test "captionize" do + assert_equal "Camel Case", captionize(:camel_case) + assert_equal "All Upper Case", captionize("all upper case") + assert_equal "With Object", captionize("With object", Object.new) + assert_not captionize("bad <title>").html_safe? end - end diff --git a/lib/generators/dry_crud/templates/test/helpers/i18n_helper_test.rb b/lib/generators/dry_crud/templates/test/helpers/i18n_helper_test.rb index b332ff5..3d05a53 100644 --- a/lib/generators/dry_crud/templates/test/helpers/i18n_helper_test.rb +++ b/lib/generators/dry_crud/templates/test/helpers/i18n_helper_test.rb @@ -1,79 +1,78 @@ -require 'test_helper' -require 'support/crud_test_model' -require 'support/crud_test_models_controller' +require "test_helper" +require "support/crud_test_model" +require "support/crud_test_models_controller" # Test I18nHelper class I18nHelperTest < ActionView::TestCase - include CrudTestHelper - test 'translate inheritable lookup' do + test "translate inheritable lookup" do # current controller is :crud_test_models, action is :index @controller = CrudTestModelsController.new I18n.backend.store_translations( I18n.locale, - global: { test_key: 'global' } + global: { test_key: "global" } ) - assert_equal 'global', ti(:test_key) + assert_equal "global", ti(:test_key) I18n.backend.store_translations( I18n.locale, - list: { global: { test_key: 'list global' } } + list: { global: { test_key: "list global" } } ) - assert_equal 'list global', ti(:test_key) + assert_equal "list global", ti(:test_key) I18n.backend.store_translations( I18n.locale, - list: { index: { test_key: 'list index' } } + list: { index: { test_key: "list index" } } ) - assert_equal 'list index', ti(:test_key) + assert_equal "list index", ti(:test_key) I18n.backend.store_translations( I18n.locale, - crud: { global: { test_key: 'crud global' } } + crud: { global: { test_key: "crud global" } } ) - assert_equal 'crud global', ti(:test_key) + assert_equal "crud global", ti(:test_key) I18n.backend.store_translations( I18n.locale, - crud: { index: { test_key: 'crud index' } } + crud: { index: { test_key: "crud index" } } ) - assert_equal 'crud index', ti(:test_key) + assert_equal "crud index", ti(:test_key) I18n.backend.store_translations( I18n.locale, - crud_test_models: { global: { test_key: 'test global' } } + crud_test_models: { global: { test_key: "test global" } } ) - assert_equal 'test global', ti(:test_key) + assert_equal "test global", ti(:test_key) I18n.backend.store_translations( I18n.locale, - crud_test_models: { index: { test_key: 'test index' } } + crud_test_models: { index: { test_key: "test index" } } ) - assert_equal 'test index', ti(:test_key) + assert_equal "test index", ti(:test_key) end - test 'translate association lookup' do + test "translate association lookup" do assoc = CrudTestModel.reflect_on_association(:companion) I18n.backend.store_translations( I18n.locale, - global: { associations: { test_key: 'global' } } + global: { associations: { test_key: "global" } } ) - assert_equal 'global', ta(:test_key, assoc) + assert_equal "global", ta(:test_key, assoc) I18n.backend.store_translations( I18n.locale, activerecord: { associations: { crud_test_model: { - test_key: 'model' + test_key: "model" } } } ) - assert_equal 'model', ta(:test_key, assoc) + assert_equal "model", ta(:test_key, assoc) I18n.backend.store_translations( I18n.locale, @@ -82,16 +81,15 @@ class I18nHelperTest < ActionView::TestCase models: { crud_test_model: { companion: { - test_key: 'companion' + test_key: "companion" } } } } } ) - assert_equal 'companion', ta(:test_key, assoc) + assert_equal "companion", ta(:test_key, assoc) - assert_equal 'global', ta(:test_key) + assert_equal "global", ta(:test_key) end - end diff --git a/lib/generators/dry_crud/templates/test/helpers/table_helper_test.rb b/lib/generators/dry_crud/templates/test/helpers/table_helper_test.rb index 7904c91..a2cb8cd 100644 --- a/lib/generators/dry_crud/templates/test/helpers/table_helper_test.rb +++ b/lib/generators/dry_crud/templates/test/helpers/table_helper_test.rb @@ -1,10 +1,9 @@ -require 'test_helper' -require 'support/custom_assertions' -require 'support/crud_test_model' +require "test_helper" +require "support/custom_assertions" +require "support/crud_test_model" # Test TableHelper class TableHelperTest < ActionView::TestCase - include UtilityHelper include FormatHelper include I18nHelper @@ -30,13 +29,13 @@ def empty_params @params = {} end - test 'empty table renders message' do + test "empty table renders message" do result = plain_table_or_message([]) assert result.html_safe? assert_match(/<div class=["']table["']>.*<\/div>/, result) end - test 'non empty table renders table' do + test "non empty table renders table" do result = plain_table_or_message(%w[foo bar]) do |t| t.attrs :size, :upcase end @@ -44,10 +43,10 @@ def empty_params assert_match(/^<table.*<\/table>$/, result) end - test 'table with attrs' do + test "table with attrs" do expected = DryCrud::Table::Builder.table( %w[foo bar], self, - class: 'table table-striped table-hover' + class: "table table-striped table-hover" ) do |t| t.attrs :size, :upcase end @@ -56,7 +55,7 @@ def empty_params assert_equal expected, actual end - test 'standard list table' do + test "standard list table" do @entries = CrudTestModel.all table = with_test_routing do @@ -67,7 +66,7 @@ def empty_params assert_count 14, REGEXP_SORT_HEADERS, table end - test 'custom list table with attributes' do + test "custom list table with attributes" do @entries = CrudTestModel.all table = with_test_routing do @@ -78,13 +77,13 @@ def empty_params assert_count 3, REGEXP_SORT_HEADERS, table end - test 'custom list table with block' do + test "custom list table with block" do @entries = CrudTestModel.all table = with_test_routing do list_table do |t| t.attrs :name, :children, :companion_id - t.col('head') { |e| tag.span(e.income.to_s) } + t.col("head") { |e| tag.span(e.income.to_s) } end end @@ -94,12 +93,12 @@ def empty_params assert_count 6, /<span>.+?<\/span>/, table end - test 'custom list table with attributes and block' do + test "custom list table with attributes and block" do @entries = CrudTestModel.all table = with_test_routing do list_table :name, :children, :companion_id do |t| - t.col('head') { |e| tag.span(e.income.to_s) } + t.col("head") { |e| tag.span(e.income.to_s) } end end @@ -109,8 +108,8 @@ def empty_params assert_count 6, /<span>.+?<\/span>/, table end - test 'standard list table with ascending sort params' do - @params = { sort: 'children', sort_dir: 'asc' } + test "standard list table with ascending sort params" do + @params = { sort: "children", sort_dir: "asc" } @entries = CrudTestModel.all table = with_test_routing do @@ -123,8 +122,8 @@ def empty_params assert_count 1, sort_header_desc, table end - test 'standard list table with descending sort params' do - @params = { sort: 'children', sort_dir: 'desc' } + test "standard list table with descending sort params" do + @params = { sort: "children", sort_dir: "desc" } @entries = CrudTestModel.all table = with_test_routing do @@ -137,8 +136,8 @@ def empty_params assert_count 1, sort_header_asc, table end - test 'list table with custom column sort params' do - @params = { sort: 'chatty', sort_dir: 'asc' } + test "list table with custom column sort params" do + @params = { sort: "chatty", sort_dir: "asc" } @entries = CrudTestModel.all table = with_test_routing do @@ -151,7 +150,7 @@ def empty_params assert_count 1, sort_header_desc, table end - test 'standard crud table' do + test "standard crud table" do @entries = CrudTestModel.all table = with_test_routing do @@ -163,7 +162,7 @@ def empty_params assert_count 12, REGEXP_ACTION_CELL, table # edit, delete links end - test 'custom crud table with attributes' do + test "custom crud table with attributes" do @entries = CrudTestModel.all table = with_test_routing do @@ -175,13 +174,13 @@ def empty_params assert_count 12, REGEXP_ACTION_CELL, table # edit, delete links end - test 'custom crud table with block' do + test "custom crud table with block" do @entries = CrudTestModel.all table = with_test_routing do crud_table do |t| t.attrs :name, :children, :companion_id - t.col('head') { |e| tag.span(e.income.to_s) } + t.col("head") { |e| tag.span(e.income.to_s) } end end @@ -191,12 +190,12 @@ def empty_params assert_count 12, REGEXP_ACTION_CELL, table # edit, delete links end - test 'custom crud table with attributes and block' do + test "custom crud table with attributes and block" do @entries = CrudTestModel.all table = with_test_routing do crud_table :name, :children, :companion_id do |t| - t.col('head') { |e| tag.span(e.income.to_s) } + t.col("head") { |e| tag.span(e.income.to_s) } end end @@ -210,5 +209,4 @@ def empty_params def entry @entry ||= CrudTestModel.first end - end diff --git a/lib/generators/dry_crud/templates/test/helpers/utility_helper_test.rb b/lib/generators/dry_crud/templates/test/helpers/utility_helper_test.rb index b301f84..c26335e 100644 --- a/lib/generators/dry_crud/templates/test/helpers/utility_helper_test.rb +++ b/lib/generators/dry_crud/templates/test/helpers/utility_helper_test.rb @@ -1,47 +1,46 @@ -require 'test_helper' -require 'support/crud_test_model' +require "test_helper" +require "support/crud_test_model" # Test UtilityHelper class UtilityHelperTest < ActionView::TestCase - include CrudTestHelper setup :reset_db, :setup_db, :create_test_data teardown :reset_db - test 'content_tag_nested escapes safe correctly' do + test "content_tag_nested escapes safe correctly" do html = content_tag_nested(:div, %w[a b]) { |e| tag.span(e) } - assert_equal '<div><span>a</span><span>b</span></div>', html + assert_equal "<div><span>a</span><span>b</span></div>", html end - test 'content_tag_nested escapes unsafe correctly' do + test "content_tag_nested escapes unsafe correctly" do html = content_tag_nested(:div, %w[a b]) { |e| "<#{e}>" } - assert_equal '<div><a><b></div>', html + assert_equal "<div><a><b></div>", html end - test 'content_tag_nested without block' do + test "content_tag_nested without block" do html = content_tag_nested(:div, %w[a b]) - assert_equal '<div>ab</div>', html + assert_equal "<div>ab</div>", html end - test 'safe_join without block' do - html = safe_join(['<a>', '<b>'.html_safe]) - assert_equal '<a><b>', html + test "safe_join without block" do + html = safe_join([ "<a>", "<b>".html_safe ]) + assert_equal "<a><b>", html end - test 'safe_join with block' do + test "safe_join with block" do html = safe_join(%w[a b]) { |e| tag.span(e) } - assert_equal '<span>a</span><span>b</span>', html + assert_equal "<span>a</span><span>b</span>", html end - test 'default attributes do not include id and password' do + test "default attributes do not include id and password" do assert_equal %i[name email whatever children companion_id rating income birthdate gets_up_at last_seen human remarks created_at updated_at], default_crud_attrs end - test 'column types' do + test "column types" do m = crud_test_models(:AAAAA) assert_equal :string, column_type(m, :name) assert_equal :integer, column_type(m, :children) @@ -55,5 +54,4 @@ class UtilityHelperTest < ActionView::TestCase assert_equal :boolean, column_type(m, :human) assert_equal :text, column_type(m, :remarks) end - end diff --git a/lib/generators/dry_crud/templates/test/support/crud_controller_test_helper.rb b/lib/generators/dry_crud/templates/test/support/crud_controller_test_helper.rb index 071ddd7..0ab0c20 100644 --- a/lib/generators/dry_crud/templates/test/support/crud_controller_test_helper.rb +++ b/lib/generators/dry_crud/templates/test/support/crud_controller_test_helper.rb @@ -3,7 +3,6 @@ # #test_entry_attrs to test the basic crud functionality. Override the test # methods if you changed the behaviour in your subclass controller. module CrudControllerTestHelper # rubocop:disable Metrics/ModuleLength - def test_index # :nodoc: get :index, params: test_params assert_response :success @@ -11,13 +10,13 @@ def test_index # :nodoc: end def test_index_json # :nodoc: - get :index, params: test_params(format: 'json') + get :index, params: test_params(format: "json") assert_response :success assert entries.present? - assert @response.body.starts_with?('[{'), @response.body + assert @response.body.starts_with?("[{"), @response.body end - def test_index_search # rubocop:disable Metrics/AbcSize :nodoc: + def test_index_search # rubocop:disable Metrics/AbcSize -- :nodoc: field = @controller.search_columns.first val = field && test_entry[field].to_s return if val.blank? # does not support search or no value in this field @@ -30,7 +29,7 @@ def test_index_search # rubocop:disable Metrics/AbcSize :nodoc: def test_index_sort_asc # :nodoc: col = model_class.column_names.first - get :index, params: test_params(sort: col, sort_dir: 'asc') + get :index, params: test_params(sort: col, sort_dir: "asc") assert_response :success assert entries.present? sorted = entries.sort_by(&col.to_sym) @@ -39,7 +38,7 @@ def test_index_sort_asc # :nodoc: def test_index_sort_desc # :nodoc: col = model_class.column_names.first - get :index, params: test_params(sort: col, sort_dir: 'desc') + get :index, params: test_params(sort: col, sort_dir: "desc") assert_response :success assert entries.present? sorted = entries.to_a.sort_by(&col.to_sym) @@ -53,10 +52,10 @@ def test_show # :nodoc: end def test_show_json # :nodoc: - get :show, params: test_params(id: test_entry.id, format: 'json') + get :show, params: test_params(id: test_entry.id, format: "json") assert_response :success assert_equal test_entry, entry - assert @response.body.starts_with?('{') + assert @response.body.starts_with?("{") end def test_show_with_non_existing_id_raises_record_not_found # :nodoc: @@ -83,7 +82,7 @@ def test_create # :nodoc: def test_create_json # :nodoc: assert_difference("#{model_class.name}.count") do post :create, params: test_params(model_identifier => new_entry_attrs, - format: 'json') + format: "json") end assert_response :success assert @response.body.starts_with?('{"id":') @@ -108,7 +107,7 @@ def test_update_json # :nodoc: assert_no_difference("#{model_class.name}.count") do put :update, params: test_params(id: test_entry.id, model_identifier => edit_entry_attrs, - format: 'json') + format: "json") end assert_response :success assert @response.body.starts_with?('{"id":') @@ -124,22 +123,22 @@ def test_destroy # :nodoc: def test_destroy_json # :nodoc: assert_difference("#{model_class.name}.count", -1) do delete :destroy, params: test_params(id: test_entry.id, - format: 'json') + format: "json") end assert_response :success - assert_equal '', @response.body.strip + assert_equal "", @response.body.strip end private def assert_redirected_to_index # :nodoc: - assert_redirected_to test_params(action: 'index', + assert_redirected_to test_params(action: "index", id: nil, returning: true) end def assert_redirected_to_show(entry) # :nodoc: - assert_redirected_to test_params(action: 'show', + assert_redirected_to test_params(action: "show", id: entry.id) end @@ -212,5 +211,4 @@ def nesting_params end params end - end diff --git a/lib/generators/dry_crud/templates/test/support/crud_test_helper.rb b/lib/generators/dry_crud/templates/test/support/crud_test_helper.rb index 6424292..493c4c4 100644 --- a/lib/generators/dry_crud/templates/test/support/crud_test_helper.rb +++ b/lib/generators/dry_crud/templates/test/support/crud_test_helper.rb @@ -8,7 +8,6 @@ # This helper is used to test the CrudController and various helpers # without the need for an application based model. module CrudTestHelper - # Controller helper methods for the tests def model_class @@ -16,11 +15,11 @@ def model_class end def controller_name - 'crud_test_models' + "crud_test_models" end def action_name - 'index' + "index" end def params @@ -35,9 +34,7 @@ def sortable?(_attr) true end - def h(text) - ERB::Util.h(text) - end + delegate :h, to: :'ERB::Util' private @@ -85,8 +82,8 @@ def create_other_crud_test_models(connection) def create_crud_test_models_other_crud_test_models(connection) connection.create_table :crud_test_models_other_crud_test_models, force: true do |t| - t.belongs_to :crud_test_model, index: { name: 'parent' } - t.belongs_to :other_crud_test_model, index: { name: 'other' } + t.belongs_to :crud_test_model, index: { name: "parent" } + t.belongs_to :other_crud_test_model, index: { name: "other" } end end @@ -116,7 +113,7 @@ def with_test_routing with_routing do |set| set.draw { resources :crud_test_models } # used to define a controller in these tests - set.default_url_options = { controller: 'crud_test_models' } + set.default_url_options = { controller: "crud_test_models" } yield end end @@ -181,16 +178,15 @@ def str(index) def without_transaction c = ActiveRecord::Base.connection start_transaction = false - if c.adapter_name.downcase.include?('mysql') && + if c.adapter_name.downcase.include?("mysql") && c.open_transactions.positive? # in transactional tests, we may simply rollback - c.execute('ROLLBACK') + c.execute("ROLLBACK") start_transaction = true end yield - c.execute('BEGIN') if start_transaction + c.execute("BEGIN") if start_transaction end - end diff --git a/lib/generators/dry_crud/templates/test/support/crud_test_model.rb b/lib/generators/dry_crud/templates/test/support/crud_test_model.rb index aef52bc..7871592 100644 --- a/lib/generators/dry_crud/templates/test/support/crud_test_model.rb +++ b/lib/generators/dry_crud/templates/test/support/crud_test_model.rb @@ -1,12 +1,11 @@ # A dummy model used for general testing. class CrudTestModel < ApplicationRecord # :nodoc: - - belongs_to :companion, class_name: 'CrudTestModel', optional: true - has_and_belongs_to_many :others, class_name: 'OtherCrudTestModel' - has_many :mores, class_name: 'OtherCrudTestModel', + belongs_to :companion, class_name: "CrudTestModel", optional: true + has_and_belongs_to_many :others, class_name: "OtherCrudTestModel" + has_many :mores, class_name: "OtherCrudTestModel", foreign_key: :more_id - has_one :comrad, class_name: 'CrudTestModel', foreign_key: :companion_id + has_one :comrad, class_name: "CrudTestModel", foreign_key: :companion_id before_destroy :protect_if_companion @@ -25,23 +24,20 @@ def chatty def protect_if_companion if companion.present? - errors.add(:base, 'Cannot destroy model with companion') + errors.add(:base, "Cannot destroy model with companion") throw :abort end end - end # Second dummy model to test associations. class OtherCrudTestModel < ApplicationRecord # :nodoc: - - has_and_belongs_to_many :others, class_name: 'CrudTestModel' + has_and_belongs_to_many :others, class_name: "CrudTestModel" belongs_to :more, - class_name: 'CrudTestModel', + class_name: "CrudTestModel", optional: true def to_s name end - end diff --git a/lib/generators/dry_crud/templates/test/support/crud_test_models_controller.rb b/lib/generators/dry_crud/templates/test/support/crud_test_models_controller.rb index f7917f6..308e810 100644 --- a/lib/generators/dry_crud/templates/test/support/crud_test_models_controller.rb +++ b/lib/generators/dry_crud/templates/test/support/crud_test_models_controller.rb @@ -1,15 +1,14 @@ # Controller for the dummy model. class CrudTestModelsController < CrudController # :nodoc: - - HANDLE_PREFIX = 'handle_'.freeze + HANDLE_PREFIX = "handle_".freeze self.search_columns = %i[name whatever remarks] - self.sort_mappings = { chatty: 'length(remarks)' } - self.default_sort = 'name' - self.permitted_attrs = [:name, :email, :password, :whatever, :children, + self.sort_mappings = { chatty: "length(remarks)" } + self.default_sort = "name" + self.permitted_attrs = [ :name, :email, :password, :whatever, :children, :companion_id, :rating, :income, :birthdate, :gets_up_at, :last_seen, :human, :remarks, - { other_ids: [] }] + { other_ids: [] } ] before_create :possibly_redirect before_create :handle_name @@ -27,16 +26,16 @@ class CrudTestModelsController < CrudController # :nodoc: def index entries - render plain: 'index js' if request.format.js? + render plain: "index js" if request.format.js? end def show - render html: 'custom html' if entry.name == 'BBBBB' + render html: "custom html" if entry.name == "BBBBB" end def create super do |_format, success| - flash[:notice] = 'model got created' if success + flash[:notice] = "model got created" if success end end @@ -45,9 +44,9 @@ def create def list_entries entries = super if params[:filter] - entries = entries.where(['rating < ?', 3]) + entries = entries.where(rating: ...3) .except(:order) - .order('children DESC') + .order("children DESC") end entries end @@ -60,15 +59,15 @@ def build_entry # custom callback def handle_name - if entry.name == 'illegal' - flash[:alert] = 'illegal name' + if entry.name == "illegal" + flash[:alert] = "illegal name" throw :abort end end # callback to redirect if @should_redirect is set def possibly_redirect - redirect_to action: 'index' if should_redirect && !performed? + redirect_to action: "index" if should_redirect && !performed? end def set_companions @@ -107,5 +106,4 @@ def called_callback(callback) @called_callbacks ||= [] @called_callbacks << callback end - end diff --git a/lib/generators/dry_crud/templates/test/support/custom_assertions.rb b/lib/generators/dry_crud/templates/test/support/custom_assertions.rb index b2ccc48..30aff1c 100644 --- a/lib/generators/dry_crud/templates/test/support/custom_assertions.rb +++ b/lib/generators/dry_crud/templates/test/support/custom_assertions.rb @@ -8,9 +8,8 @@ # # inside the class definition: # include CustomAssertions module CustomAssertions - # Asserts that regexp occurs exactly expected times in string. - def assert_count(expected, regexp, string, msg = '') + def assert_count(expected, regexp, string, msg = "") actual = string.scan(regexp).size msg = message(msg) do "Expected #{mu_pp(regexp)} to occur #{expected} time(s), " \ @@ -21,7 +20,7 @@ def assert_count(expected, regexp, string, msg = '') # Asserts that the given active model record is valid. # This method used to be part of Rails but was deprecated, no idea why. - def assert_valid(record, msg = '') + def assert_valid(record, msg = "") record.valid? msg = message(msg) do "Expected #{mu_pp(record)} to be valid, " \ @@ -77,5 +76,4 @@ def assert_other_attrs_have_no_errors(record, *invalid_attrs) assert invalid_attrs.include?(error.attribute), msg end end - end diff --git a/test/templates/Gemfile.append b/test/templates/Gemfile.append index e98f94a..d42476d 100644 --- a/test/templates/Gemfile.append +++ b/test/templates/Gemfile.append @@ -1,14 +1,14 @@ -gem 'dry_crud', path: '../..' +gem "dry_crud", path: "../.." -gem 'simplecov', require: false, group: :test +gem "simplecov", require: false, group: :test platforms :jruby do - gem 'jdbc-sqlite3' - gem 'activerecord-jdbcsqlite3-adapter' + gem "jdbc-sqlite3" + gem "activerecord-jdbcsqlite3-adapter" end -gem 'haml' +gem "haml" -gem 'kaminari' +gem "kaminari" -gem 'rspec-rails' +gem "rspec-rails" diff --git a/test/templates/app/controllers/admin/cities_controller.rb b/test/templates/app/controllers/admin/cities_controller.rb index 49e2dcf..aedad64 100644 --- a/test/templates/app/controllers/admin/cities_controller.rb +++ b/test/templates/app/controllers/admin/cities_controller.rb @@ -3,9 +3,9 @@ module Admin class CitiesController < TurboController self.nesting = :admin, Country - self.search_columns = :name, 'countries.name' + self.search_columns = :name, "countries.name" - self.default_sort = 'countries.code, cities.name' + self.default_sort = "countries.code, cities.name" self.permitted_attrs = %i[name person_ids] diff --git a/test/templates/app/controllers/admin/countries_controller.rb b/test/templates/app/controllers/admin/countries_controller.rb index 902c703..8ff382a 100644 --- a/test/templates/app/controllers/admin/countries_controller.rb +++ b/test/templates/app/controllers/admin/countries_controller.rb @@ -5,7 +5,7 @@ class CountriesController < TurboController self.search_columns = :name, :code - self.default_sort = 'countries.name' + self.default_sort = "countries.name" self.permitted_attrs = %i[name code] diff --git a/test/templates/app/controllers/people_controller.rb b/test/templates/app/controllers/people_controller.rb index 902e170..c127b34 100644 --- a/test/templates/app/controllers/people_controller.rb +++ b/test/templates/app/controllers/people_controller.rb @@ -1,10 +1,10 @@ # People Controller class PeopleController < TurboController - self.search_columns = [:name, :email, :remarks, 'cities.name'] + self.search_columns = [ :name, :email, :remarks, "cities.name" ] - self.default_sort = 'people.name, countries.code, cities.name' + self.default_sort = "people.name, countries.code, cities.name" - self.sort_mappings = { city_id: 'cities.name' } + self.sort_mappings = { city_id: "cities.name" } self.permitted_attrs = %i[name children city_id rating income birthdate gets_up_at last_seen remarks diff --git a/test/templates/app/controllers/vips_controller.rb b/test/templates/app/controllers/vips_controller.rb index 56733f9..b143825 100644 --- a/test/templates/app/controllers/vips_controller.rb +++ b/test/templates/app/controllers/vips_controller.rb @@ -1,10 +1,10 @@ # List Controller for VIP people class VipsController < ListController - self.search_columns = [:name, :children, :rating, :remarks, 'cities.name'] + self.search_columns = [ :name, :children, :rating, :remarks, "cities.name" ] - self.sort_mappings = { city_id: 'cities.name' } + self.sort_mappings = { city_id: "cities.name" } - self.default_sort = 'people.name, countries.code, cities.name' + self.default_sort = "people.name, countries.code, cities.name" private @@ -15,7 +15,7 @@ def model_class end def list_entries - list = super.where('rating > 5').includes(city: :country) + list = super.where("rating > 5").includes(city: :country) if list.respond_to?(:references) list = list.references(:cities, :countries) end diff --git a/test/templates/app/helpers/people_helper.rb b/test/templates/app/helpers/people_helper.rb index da6c00c..6e50063 100644 --- a/test/templates/app/helpers/people_helper.rb +++ b/test/templates/app/helpers/people_helper.rb @@ -7,8 +7,8 @@ def format_person_income(person) def f(value) case value - when true then 'iu' - else super(value) + when true then "iu" + else super end end end diff --git a/test/templates/app/models/city.rb b/test/templates/app/models/city.rb index f8e2b0a..315f14d 100644 --- a/test/templates/app/models/city.rb +++ b/test/templates/app/models/city.rb @@ -7,7 +7,7 @@ class City < ApplicationRecord before_destroy :protect_with_inhabitants - scope :options_list, -> { includes(:country).order('cities.name') } + scope :options_list, -> { includes(:country).order("cities.name") } def to_s "#{name} (#{country.code})" diff --git a/test/templates/app/models/person.rb b/test/templates/app/models/person.rb index 796db01..ec5734b 100644 --- a/test/templates/app/models/person.rb +++ b/test/templates/app/models/person.rb @@ -4,7 +4,7 @@ class Person < ApplicationRecord validates :name, presence: true - scope :list, -> { order('people.name') } + scope :list, -> { order("people.name") } def to_s name diff --git a/test/templates/config/initializers/deprecations.rb b/test/templates/config/initializers/deprecations.rb index 26d055d..b665119 100644 --- a/test/templates/config/initializers/deprecations.rb +++ b/test/templates/config/initializers/deprecations.rb @@ -6,4 +6,4 @@ # config.active_record.time_zone_aware_types = [:datetime] # To silence this deprecation warning, add the following: -Rails.application.config.active_record.time_zone_aware_types = [:datetime, :time] +Rails.application.config.active_record.time_zone_aware_types = [ :datetime, :time ] diff --git a/test/templates/config/routes.rb b/test/templates/config/routes.rb index 0dbc03b..2b28598 100644 --- a/test/templates/config/routes.rb +++ b/test/templates/config/routes.rb @@ -1,14 +1,13 @@ # encoding: UTF-8 TestApp::Application.routes.draw do - resources :people do collection do get :turbo end end - get 'vips' => 'vips#index', :as => :vips + get "vips" => "vips#index", :as => :vips namespace :admin do resources :countries do @@ -24,7 +23,7 @@ end end - root to: 'people#index' + root to: "people#index" # Install the default routes as the lowest priority. # Note: These default routes make all actions in every controller accessible diff --git a/test/templates/db/seeds.rb b/test/templates/db/seeds.rb index 80795a2..f12fd65 100644 --- a/test/templates/db/seeds.rb +++ b/test/templates/db/seeds.rb @@ -2,75 +2,75 @@ if City.count == 0 -ch = Country.create!(name: 'Switzerland', code: 'CH') -de = Country.create!(name: 'Germany', code: 'DE') -usa = Country.create!(name: 'USA', code: 'USA') -gb = Country.create!(name: 'England', code: 'GB') -jp = Country.create!(name: 'Japan', code: 'JP') +ch = Country.create!(name: "Switzerland", code: "CH") +de = Country.create!(name: "Germany", code: "DE") +usa = Country.create!(name: "USA", code: "USA") +gb = Country.create!(name: "England", code: "GB") +jp = Country.create!(name: "Japan", code: "JP") -be = City.create!(name: 'Bern', country: ch) -ny = City.create!(name: 'New York', country: usa) -sf = City.create!(name: 'San Francisco', country: usa) -lon = City.create!(name: 'London', country: gb) -br = City.create!(name: 'Berlin', country: de) +be = City.create!(name: "Bern", country: ch) +ny = City.create!(name: "New York", country: usa) +sf = City.create!(name: "San Francisco", country: usa) +lon = City.create!(name: "London", country: gb) +br = City.create!(name: "Berlin", country: de) -Person.create!(name: 'Albert Einstein', +Person.create!(name: "Albert Einstein", city: be, children: 2, rating: 9.8, income: 84_000, - birthdate: '1904-10-18', - gets_up_at: '05:43', + birthdate: "1904-10-18", + gets_up_at: "05:43", remarks: "Great physician\n Good cyclist") -Person.create!(name: 'Adolf Ogi', +Person.create!(name: "Adolf Ogi", city: be, children: 3, rating: 4.2, income: 264_000, - birthdate: '1938-01-22', - gets_up_at: '04:30', - remarks: 'Freude herrscht!') -Person.create!(name: 'Jay Z', + birthdate: "1938-01-22", + gets_up_at: "04:30", + remarks: "Freude herrscht!") +Person.create!(name: "Jay Z", city: ny, children: 0, rating: 7.2, income: 868_345, - birthdate: '1976-05-02', - gets_up_at: '12:00', - last_seen: '2011-03-10 17:29', + birthdate: "1976-05-02", + gets_up_at: "12:00", + last_seen: "2011-03-10 17:29", cool: true, remarks: "I got 99 problems\nbut you *** ain't one\nTschie") -Person.create!(name: 'Queen Elisabeth', +Person.create!(name: "Queen Elisabeth", city: lon, children: 1, rating: 1.56, income: 345_622, - birthdate: '1927-08-11', - gets_up_at: '17:12', - remarks: '') -Person.create!(name: 'Schopenhauer', + birthdate: "1927-08-11", + gets_up_at: "17:12", + remarks: "") +Person.create!(name: "Schopenhauer", city: br, children: 7, rating: 6.9, income: 14_000, - birthdate: '1788-10-18', - last_seen: '1854-09-01 11:01', - remarks: 'Neminem laede, immo omnes, quantum potes, iuva.') -Person.create!(name: 'ZZ Top', + birthdate: "1788-10-18", + last_seen: "1854-09-01 11:01", + remarks: "Neminem laede, immo omnes, quantum potes, iuva.") +Person.create!(name: "ZZ Top", city: ny, children: 185, rating: 1.8, income: 84_000, - birthdate: '1948-03-18', + birthdate: "1948-03-18", cool: true, - remarks: 'zzz..') -Person.create!(name: 'Andy Warhol', + remarks: "zzz..") +Person.create!(name: "Andy Warhol", city: ny, children: 0, rating: 7.5, income: 123_000, - birthdate: '1938-09-08', - last_seen: '1984-10-10 23:39', - remarks: 'Tomato Soup') + birthdate: "1938-09-08", + last_seen: "1984-10-10 23:39", + remarks: "Tomato Soup") -end \ No newline at end of file +end diff --git a/test/templates/spec/.rubocop.yml b/test/templates/spec/.rubocop.yml deleted file mode 100644 index 23e2d80..0000000 --- a/test/templates/spec/.rubocop.yml +++ /dev/null @@ -1,57 +0,0 @@ -require: - - rubocop-rails - -AllCops: - DisplayCopNames: true - NewCops: enable - Exclude: - # File generated by Rails - - spec_helper.rb - -Metrics/ModuleLength: - Max: 150 - -Metrics/MethodLength: - Max: 25 - -Metrics/BlockLength: - Enabled: false - -Metrics/AbcSize: - Max: 20 - -Layout/EmptyLinesAroundClassBody: - Enabled: false - -Layout/EmptyLinesAroundModuleBody: - Enabled: false - -Layout/EmptyLinesAroundBlockBody: - Enabled: false - -Layout/ParameterAlignment: - Enabled: false - -Layout/SpaceBeforeFirstArg: - Enabled: false - -Lint/Void: - Enabled: false - -Rails/OutputSafety: - Enabled: false - -Style/ClassVars: - Enabled: false - -Style/GuardClause: - Enabled: false - -Style/RegexpLiteral: - Enabled: false - -Style/FrozenStringLiteralComment: - Enabled: false - -Style/SafeNavigation: - Enabled: false diff --git a/test/templates/spec/controllers/admin/cities_controller_spec.rb b/test/templates/spec/controllers/admin/cities_controller_spec.rb index ec17729..53d2d79 100644 --- a/test/templates/spec/controllers/admin/cities_controller_spec.rb +++ b/test/templates/spec/controllers/admin/cities_controller_spec.rb @@ -1,52 +1,52 @@ -require 'rails_helper' +require "rails_helper" describe Admin::CitiesController do fixtures :all - include_examples 'crud controller', {} + include_examples "crud controller", {} let(:test_entry) { cities(:rj) } - let(:test_entry_attrs) { { name: 'Rejkiavik' } } + let(:test_entry_attrs) { { name: "Rejkiavik" } } alias_method :new_entry_attrs, :test_entry_attrs alias_method :edit_entry_attrs, :test_entry_attrs - it 'loads fixtures' do + it "loads fixtures" do expect(City.count).to eq(3) end describe_action :get, :index do - it 'is ordered by default scope' do + it "is ordered by default scope" do expected = test_entry.country.cities.includes(:country) - .order('countries.code, cities.name') + .order("countries.code, cities.name") expected = expected.references(:countries) if expected.respond_to?(:references) entries == expected end - it 'sets parents' do - expect(controller.send(:parents)).to eq([:admin, test_entry.country]) + it "sets parents" do + expect(controller.send(:parents)).to eq([ :admin, test_entry.country ]) end - it 'sets parent variable' do + it "sets parent variable" do expect(ivar(:country)).to eq(test_entry.country) end - it 'uses correct model_scope' do + it "uses correct model_scope" do expect(controller.send(:model_scope)).to eq(test_entry.country.cities) end - it 'has correct path args' do + it "has correct path args" do expect(controller.send(:path_args, 2)).to eq( - [:admin, test_entry.country, 2] + [ :admin, test_entry.country, 2 ] ) end end describe_action :get, :show, id: true do - it 'sets parents' do - expect(controller.send(:parents)).to eq([:admin, test_entry.country]) + it "sets parents" do + expect(controller.send(:parents)).to eq([ :admin, test_entry.country ]) end - it 'sets parent variable' do + it "sets parent variable" do expect(ivar(:country)).to eq(test_entry.country) end end @@ -54,21 +54,21 @@ describe_action :post, :create do let(:params) { { model_identifier => new_entry_attrs } } - it 'sets parent' do + it "sets parent" do expect(entry.country).to eq(test_entry.country) end end describe_action :delete, :destroy, id: true do - context 'with inhabitants' do + context "with inhabitants" do let(:test_entry) { cities(:ny) } - it 'does not remove city from database', perform_request: false do + it "does not remove city from database", perform_request: false do expect { perform_request }.to change { City.count }.by(0) end - it 'redirects to referer', perform_request: false do - ref = @request.env['HTTP_REFERER'] = + it "redirects to referer", perform_request: false do + ref = @request.env["HTTP_REFERER"] = admin_country_city_url(test_entry.country, test_entry) perform_request is_expected.to redirect_to(ref) diff --git a/test/templates/spec/controllers/admin/countries_controller_spec.rb b/test/templates/spec/controllers/admin/countries_controller_spec.rb index d3f4828..ac073b3 100644 --- a/test/templates/spec/controllers/admin/countries_controller_spec.rb +++ b/test/templates/spec/controllers/admin/countries_controller_spec.rb @@ -1,41 +1,41 @@ -require 'rails_helper' +require "rails_helper" describe Admin::CountriesController do fixtures :all - include_examples 'crud controller', skip: %w[show html plain] + include_examples "crud controller", skip: %w[show html plain] let(:test_entry) { countries(:br) } let(:test_entry_attrs) do - { name: 'United States of America', code: 'US' } + { name: "United States of America", code: "US" } end alias_method :new_entry_attrs, :test_entry_attrs alias_method :edit_entry_attrs, :test_entry_attrs - it 'loads fixtures' do + it "loads fixtures" do expect(Country.count).to eq(3) end describe_action :get, :index do - it 'is ordered by default scope' do + it "is ordered by default scope" do entries == Country.order(:name) end - it 'sets parents' do - expect(controller.send(:parents)).to eq([:admin]) + it "sets parents" do + expect(controller.send(:parents)).to eq([ :admin ]) end - it 'sets nil parent' do + it "sets nil parent" do expect(controller.send(:parent)).to be_nil end - it 'uses correct model_scope' do + it "uses correct model_scope" do expect(controller.send(:model_scope)).to eq(Country.all) end - it 'has correct path args' do - expect(controller.send(:path_args, 2)).to eq([:admin, 2]) + it "has correct path args" do + expect(controller.send(:path_args, 2)).to eq([ :admin, 2 ]) end end diff --git a/test/templates/spec/controllers/people_controller_spec.rb b/test/templates/spec/controllers/people_controller_spec.rb index 99943ec..149d50c 100644 --- a/test/templates/spec/controllers/people_controller_spec.rb +++ b/test/templates/spec/controllers/people_controller_spec.rb @@ -1,15 +1,15 @@ -require 'rails_helper' +require "rails_helper" describe PeopleController do fixtures :all render_views - include_examples 'crud controller', {} + include_examples "crud controller", {} let(:test_entry) { people(:john) } let(:test_entry_attrs) do - { name: 'Fischers Fritz', + { name: "Fischers Fritz", children: 2, income: 120, city_id: cities(:rj).id } @@ -18,60 +18,60 @@ alias_method :new_entry_attrs, :test_entry_attrs alias_method :edit_entry_attrs, :test_entry_attrs - it 'loads fixtures' do + it "loads fixtures" do expect(Person.count).to eq(2) end describe_action :get, :index do - it 'is ordered by default scope' do + it "is ordered by default scope" do expected = Person.includes(city: :country) - .order('people.name, countries.code, cities.name') + .order("people.name, countries.code, cities.name") expected = expected.references(:cities, :countries) if expected.respond_to?(:references) entries == expected end - it 'sets parents' do + it "sets parents" do expect(controller.send(:parents)).to eq([]) end - it 'sets nil parent' do + it "sets nil parent" do expect(controller.send(:parent)).to be_nil end - it 'uses correct model_scope' do + it "uses correct model_scope" do expect(controller.send(:model_scope)).to eq(Person.all) end - it 'has correct path args' do - expect(controller.send(:path_args, 2)).to eq([2]) + it "has correct path args" do + expect(controller.send(:path_args, 2)).to eq([ 2 ]) end end describe_action :get, :show, id: true do - context 'turbo', format: :turbo_stream do + context "turbo", format: :turbo_stream do it_is_expected_to_respond it { expect(response.body).to match(/<turbo-stream action="update" target="content">/) } end end describe_action :get, :edit, id: true do - context 'turbo', format: :turbo_stream do + context "turbo", format: :turbo_stream do it_is_expected_to_respond it { expect(response.body).to match(/<turbo-stream action="update" target="content">/) } end end describe_action :put, :update, id: true do - context 'turbo', format: :turbo_stream do - context 'with valid params' do - let(:params) { { person: { name: 'New Name' } } } + context "turbo", format: :turbo_stream do + context "with valid params" do + let(:params) { { person: { name: "New Name" } } } it_is_expected_to_respond it { expect(response.body).to match(/<turbo-stream action="update" target="content">/) } end - context 'with invalid params' do - let(:params) { { person: { name: ' ' } } } + context "with invalid params" do + let(:params) { { person: { name: " " } } } it_is_expected_to_respond it { expect(response.body).to match(/<turbo-stream action="update" target="content">/) } diff --git a/test/templates/spec/routing/cities_routing_spec.rb b/test/templates/spec/routing/cities_routing_spec.rb index a18e5ce..400049c 100644 --- a/test/templates/spec/routing/cities_routing_spec.rb +++ b/test/templates/spec/routing/cities_routing_spec.rb @@ -1,15 +1,15 @@ -require 'rails_helper' +require "rails_helper" describe Admin::CitiesController do - it 'routes index' do - expect(get: 'admin/countries/1/cities').to route_to( - controller: 'admin/cities', action: 'index', country_id: '1' + it "routes index" do + expect(get: "admin/countries/1/cities").to route_to( + controller: "admin/cities", action: "index", country_id: "1" ) end - it 'routes show' do - expect(get: 'admin/countries/2/cities/1').to route_to( - controller: 'admin/cities', action: 'show', country_id: '2', id: '1' + it "routes show" do + expect(get: "admin/countries/2/cities/1").to route_to( + controller: "admin/cities", action: "show", country_id: "2", id: "1" ) end end diff --git a/test/templates/spec/routing/countries_routing_spec.rb b/test/templates/spec/routing/countries_routing_spec.rb index 67e45d9..86d0fda 100644 --- a/test/templates/spec/routing/countries_routing_spec.rb +++ b/test/templates/spec/routing/countries_routing_spec.rb @@ -1,15 +1,15 @@ -require 'rails_helper' +require "rails_helper" describe Admin::CountriesController do - it 'routes index' do - expect(get: 'admin/countries').to route_to( - controller: 'admin/countries', action: 'index' + it "routes index" do + expect(get: "admin/countries").to route_to( + controller: "admin/countries", action: "index" ) end - it 'routes show' do - expect(get: 'admin/countries/1').to route_to( - controller: 'admin/countries', action: 'show', id: '1' + it "routes show" do + expect(get: "admin/countries/1").to route_to( + controller: "admin/countries", action: "show", id: "1" ) end end diff --git a/test/templates/test/.rubocop.yml b/test/templates/test/.rubocop.yml deleted file mode 100644 index 782caf9..0000000 --- a/test/templates/test/.rubocop.yml +++ /dev/null @@ -1,56 +0,0 @@ -require: - - rubocop-rails - -AllCops: - DisplayCopNames: true - NewCops: enable - Exclude: - # File generated by Rails - - test_helper.rb - -Metrics/BlockLength: - Enabled: false - -Metrics/ClassLength: - Max: 300 - -Metrics/ModuleLength: - Max: 150 - -Metrics/MethodLength: - Max: 25 - -Metrics/AbcSize: - Max: 20 - Exclude: - - '**/*_test.rb' - -Layout/EmptyLinesAroundClassBody: - Enabled: false - -Layout/EmptyLinesAroundModuleBody: - Enabled: false - -Layout/ParameterAlignment: - Enabled: false - -Layout/SpaceBeforeFirstArg: - Enabled: false - -Rails/ActionControllerTestCase: - Enabled: false - -Rails/OutputSafety: - Enabled: false - -Style/ClassVars: - Enabled: false - -Style/GuardClause: - Enabled: false - -Style/RegexpLiteral: - Enabled: false - -Style/FrozenStringLiteralComment: - Enabled: false diff --git a/test/templates/test/controllers/admin/cities_controller_test.rb b/test/templates/test/controllers/admin/cities_controller_test.rb index e82f635..f106822 100644 --- a/test/templates/test/controllers/admin/cities_controller_test.rb +++ b/test/templates/test/controllers/admin/cities_controller_test.rb @@ -1,5 +1,5 @@ -require 'test_helper' -require 'support/crud_controller_test_helper' +require "test_helper" +require "support/crud_controller_test_helper" module Admin # Cities Controller Test @@ -8,35 +8,35 @@ class CitiesControllerTest < ActionController::TestCase def test_setup assert_equal 3, City.count - assert_recognizes({ controller: 'admin/cities', - action: 'index', - country_id: '1' }, - 'admin/countries/1/cities') - assert_recognizes({ controller: 'admin/cities', - action: 'show', - country_id: '2', - id: '1' }, - 'admin/countries/2/cities/1') + assert_recognizes({ controller: "admin/cities", + action: "index", + country_id: "1" }, + "admin/countries/1/cities") + assert_recognizes({ controller: "admin/cities", + action: "show", + country_id: "2", + id: "1" }, + "admin/countries/2/cities/1") end def test_index super expected = test_entry.country.cities.includes(:country) - .order('countries.code, cities.name') + .order("countries.code, cities.name") expected = expected.references(:countries) if expected.respond_to?(:references) assert_equal expected.to_a, entries.to_a - assert_equal [:admin, test_entry.country], @controller.send(:parents) + assert_equal [ :admin, test_entry.country ], @controller.send(:parents) assert_equal test_entry.country, @controller.send(:parent) assert_equal test_entry.country.cities.to_a, @controller.send(:model_scope).to_a - assert_equal [:admin, test_entry.country, 2], + assert_equal [ :admin, test_entry.country, 2 ], @controller.send(:path_args, 2) end def test_show super - assert_equal [:admin, test_entry.country], @controller.send(:parents) + assert_equal [ :admin, test_entry.country ], @controller.send(:parents) assert_equal test_entry.country, @controller.send(:parent) end @@ -47,11 +47,11 @@ def test_create def test_destroy_with_inhabitants ny = cities(:ny) - assert_no_difference('City.count') do - @request.env['HTTP_REFERER'] = admin_country_city_url(ny.country, ny) + assert_no_difference("City.count") do + @request.env["HTTP_REFERER"] = admin_country_city_url(ny.country, ny) delete :destroy, params: { country_id: ny.country_id, id: ny.id } end - assert_redirected_to [:admin, ny.country, ny] + assert_redirected_to [ :admin, ny.country, ny ] assert flash[:alert].present? end @@ -62,7 +62,7 @@ def test_entry end def test_entry_attrs - { name: 'Rejkiavik' } + { name: "Rejkiavik" } end end end diff --git a/test/templates/test/controllers/admin/countries_controller_test.rb b/test/templates/test/controllers/admin/countries_controller_test.rb index 42ebb80..f4c2145 100644 --- a/test/templates/test/controllers/admin/countries_controller_test.rb +++ b/test/templates/test/controllers/admin/countries_controller_test.rb @@ -1,5 +1,5 @@ -require 'test_helper' -require 'support/crud_controller_test_helper' +require "test_helper" +require "support/crud_controller_test_helper" module Admin # Countries Controller Test @@ -8,22 +8,22 @@ class CountriesControllerTest < ActionController::TestCase def test_setup assert_equal 3, Country.count - assert_recognizes({ controller: 'admin/countries', - action: 'index' }, - 'admin/countries') - assert_recognizes({ controller: 'admin/countries', - action: 'show', - id: '1' }, - 'admin/countries/1') + assert_recognizes({ controller: "admin/countries", + action: "index" }, + "admin/countries") + assert_recognizes({ controller: "admin/countries", + action: "show", + id: "1" }, + "admin/countries/1") end def test_index super - assert_equal Country.order('name').to_a, entries - assert_equal [:admin], @controller.send(:parents) + assert_equal Country.order("name").to_a, entries + assert_equal [ :admin ], @controller.send(:parents) assert_nil @controller.send(:parent) assert_equal Country.all, @controller.send(:model_scope) - assert_equal [:admin, 2], @controller.send(:path_args, 2) + assert_equal [ :admin, 2 ], @controller.send(:path_args, 2) end def test_show @@ -38,7 +38,7 @@ def test_entry end def test_entry_attrs - { name: 'United States of America', code: 'US' } + { name: "United States of America", code: "US" } end end end diff --git a/test/templates/test/controllers/people_controller_test.rb b/test/templates/test/controllers/people_controller_test.rb index 70b12d4..e2d28c5 100644 --- a/test/templates/test/controllers/people_controller_test.rb +++ b/test/templates/test/controllers/people_controller_test.rb @@ -1,5 +1,5 @@ -require 'test_helper' -require 'support/crud_controller_test_helper' +require "test_helper" +require "support/crud_controller_test_helper" # People Controller Test class PeopleControllerTest < ActionController::TestCase @@ -7,27 +7,27 @@ class PeopleControllerTest < ActionController::TestCase def test_setup assert_equal 2, Person.count - assert_recognizes({ controller: 'people', - action: 'index' }, - '/people') - assert_recognizes({ controller: 'people', - action: 'show', - id: '1' }, - '/people/1') + assert_recognizes({ controller: "people", + action: "index" }, + "/people") + assert_recognizes({ controller: "people", + action: "show", + id: "1" }, + "/people/1") end def test_index super assert_equal 2, entries.size expected = Person.includes(city: :country) - .order('people.name, countries.code, cities.name') + .order("people.name, countries.code, cities.name") expected = expected.references(:cities, :countries) if expected.respond_to?(:references) assert_equal expected.to_a, entries assert_equal [], @controller.send(:parents) assert_nil @controller.send(:parent) assert_equal Person.all, @controller.send(:model_scope) - assert_equal [2], @controller.send(:path_args, 2) + assert_equal [ 2 ], @controller.send(:path_args, 2) end def test_index_search @@ -51,7 +51,7 @@ def test_update_turbo put :update, as: :turbo_stream, params: { id: test_entry.id, - person: { name: 'New Name' } } + person: { name: "New Name" } } assert_response :success assert_match(/<turbo-stream action="update" target="content">/, response.body) end @@ -60,7 +60,7 @@ def test_update_fail_turbo put :update, as: :turbo_stream, params: { id: test_entry.id, - person: { name: ' ' } } + person: { name: " " } } assert_response :success assert_match(/alert/, response.body) end @@ -72,7 +72,7 @@ def test_entry end def test_entry_attrs - { name: 'Fischers Fritz', + { name: "Fischers Fritz", children: 2, income: 120, city_id: cities(:rj).id }