aboutsummaryrefslogtreecommitdiffstats
path: root/railties/lib/rails/generators/test_unit/scaffold/scaffold_generator.rb
blob: 9772317053a908041ecb5a55630818797c6061ae (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# frozen_string_literal: true
require "rails/generators/test_unit"
require "rails/generators/resource_helpers"

module TestUnit # :nodoc:
  module Generators # :nodoc:
    class ScaffoldGenerator < Base # :nodoc:
      include Rails::Generators::ResourceHelpers

      check_class_collision suffix: "ControllerTest"

      class_option :api, type: :boolean,
                         desc: "Generates API functional tests"

      class_option :system_tests, type: :string,
                         desc: "Skip system test files"

      argument :attributes, type: :array, default: [], banner: "field:type field:type"

      def create_test_files
        template_file = options.api? ? "api_functional_test.rb" : "functional_test.rb"
        template template_file,
                 File.join("test/controllers", controller_class_path, "#{controller_file_name}_controller_test.rb")

        unless options.api? || options[:system_tests].nil?
          template "system_test.rb", File.join("test/system", class_path, "#{file_name.pluralize}_test.rb")
        end
      end

      def fixture_name
        @fixture_name ||=
          if mountable_engine?
            (namespace_dirs + [table_name]).join("_")
          else
            table_name
          end
      end

      private

        def attributes_string
          attributes_hash.map { |k, v| "#{k}: #{v}" }.join(", ")
        end

        def attributes_hash
          return {} if attributes_names.empty?

          attributes_names.map do |name|
            if %w(password password_confirmation).include?(name) && attributes.any?(&:password_digest?)
              ["#{name}", "'secret'"]
            else
              ["#{name}", "@#{singular_table_name}.#{name}"]
            end
          end.sort.to_h
        end
    end
  end
end