From 9ad57a8d28b7ea307ae8db5a75b1a0de36f12030 Mon Sep 17 00:00:00 2001 From: Michael Kohl Date: Wed, 4 Nov 2020 00:26:08 +0700 Subject: [PATCH] Add --spec option for data_update generator (#11245) --- docs/backend/data-update-scripts.md | 20 +++++++++++++++++++ .../data_update/data_update_generator.rb | 15 ++++++++++++-- .../templates/data_update_spec.rb.tt | 8 ++++++++ 3 files changed, 41 insertions(+), 2 deletions(-) create mode 100644 lib/generators/data_update/templates/data_update_spec.rb.tt diff --git a/docs/backend/data-update-scripts.md b/docs/backend/data-update-scripts.md index 3c3d698d4..ceb7e1b5e 100644 --- a/docs/backend/data-update-scripts.md +++ b/docs/backend/data-update-scripts.md @@ -40,6 +40,26 @@ module DataUpdateScripts end ``` +The generator will also automatically create the corresponding spec file. + +```ruby +require "rails_helper" +require Rails.root.join( + "20201103042915_backfill_column_for_articles.rb", +) + +describe DataUpdateScripts::BackfillColumnForArticles do + pending "add some examples to (or delete) #{__FILE__}" +end +``` + +While we encourage adding tests for data update scripts, you can skip spec +creation by adding the `--no-spec` option to the `rails generate` command: + +``` +rails generate data_update BackfillColumnForArticles --no-spec +``` + Once your script is in place then you can either run `rails data_updates:run` manually or you can let our setup script handle it. In our local [bin/setup](https://github.com/forem/forem/blob/master/bin/setup) script you diff --git a/lib/generators/data_update/data_update_generator.rb b/lib/generators/data_update/data_update_generator.rb index a85823e94..40b92be8d 100644 --- a/lib/generators/data_update/data_update_generator.rb +++ b/lib/generators/data_update/data_update_generator.rb @@ -1,11 +1,22 @@ class DataUpdateGenerator < Rails::Generators::NamedBase source_root File.expand_path("templates", __dir__) + class_option :spec, type: :boolean, default: true def create_data_update_file template( "data_update.rb.tt", - File.join("lib", "data_update_scripts", class_path, - "#{Time.current.utc.strftime('%Y%m%d%H%M%S')}_#{file_name}.rb"), + File.join("lib", "data_update_scripts", class_path, script_name), + ) + + return unless options["spec"] + + template( + "data_update_spec.rb.tt", + File.join("spec", "lib", "data_update_scripts", class_path, "#{file_name}_spec.rb"), ) end + + def script_name + @script_name ||= "#{Time.current.utc.strftime('%Y%m%d%H%M%S')}_#{file_name}.rb" + end end diff --git a/lib/generators/data_update/templates/data_update_spec.rb.tt b/lib/generators/data_update/templates/data_update_spec.rb.tt new file mode 100644 index 000000000..f4004910c --- /dev/null +++ b/lib/generators/data_update/templates/data_update_spec.rb.tt @@ -0,0 +1,8 @@ +require "rails_helper" +require Rails.root.join( + "<%= script_name %>", +) + +describe DataUpdateScripts::<%= class_name %> do + pending "add some examples to (or delete) #{__FILE__}" +end