1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00
rails--rails/railties/test/generators/scaffold_generator_test.rb
David Heinemeier Hansson 164c2f6257
Modernize scaffold generator (#41210)
* Slim down scaffold css

To prevent conflicts with utility frameworks that might also be resetting base elements.

* Use a box-style partial rather than a table

Shows the usage of partials right from the start. Better compatibility with upgrading to Turbo frames/stream updates.

* Correct use of quotes

* Use modern array-of-strings declaration

* Use double quotes for everything

* Fix syntax

* Remove outdated viewport declaration

This should be handled in app stylesheets.

* Use double quotes everywhere

* Use symbols not strings for before_action scoping

* Use human name to deal with double word records

* Grab test fixes from #41219

Thanks @abhaynikam 🙏

* Fix tests

* Use locar var not ivar

* Fix capitalization change

* Update railties/lib/rails/generators/rails/app/templates/app/views/layouts/application.html.erb.tt

Co-authored-by: Haroon Ahmed <haroon.ahmed25@gmail.com>

* Update railties/test/generators/scaffold_controller_generator_test.rb

Co-authored-by: Haroon Ahmed <haroon.ahmed25@gmail.com>

* Update railties/test/generators/scaffold_controller_generator_test.rb

Co-authored-by: Haroon Ahmed <haroon.ahmed25@gmail.com>

* Fix test

* Update railties/test/generators/scaffold_generator_test.rb

Co-authored-by: Jonathan Hefner <jonathan@hefner.pro>

* Correct logic warning about initializers

Defining initializer 4 to run before itself and after 3 is possible, but
not when the before constraint contradicts the after constraint via 2.

* Rename master to main in all code references

* Use length == 0 instead of empty in Preloader

Previously we were checking empty? on the association which would make a
query. Instead we can check length == 0 to ensure we are using the
length of the loaded records and not issuing extra queries.

Co-authored-by: Dinah Shi <dinahshi@github.com>

* Add regression tests for preloader query count

* ActionCable guides suggest test adapter for test env [ci skip]

* Changing 'rails new' --master to be --main

Renaming test containing flag

Updating other test referencing master branch

Add notice that --master is deprecated, but still working the same as --main

Only set @main if it's nil

Making warn wildcard

I think a hidden aliaes would be just as good

Improving description & fixing rubocop error

Forgot comma

Deprecation warning was kind of hard - so just doing alias for now

rubocop -a

* I think passing in the --master argument to run_generator is the way to go

* Removing .count to figure out why its failing

* Raise unknown type error on the definition time

If unknow type is given for attribute (`attribute :foo, :unknown`),
unknown type error isn't raised on the definition time but runtime.

It should be raised on the definition time.

* Refactor `attribute` not to reference `&block`

* Use major + minor AR versions in 'Directly inheriting' error message

* Raise error when passing passing a class to :source_type

Raise `ArgumentError` when `:source_type` is given as class
in `has_many :through` relation.

Closes #41092

* Adding badges and logo to README and CONTRIBUTING page

* switch references to main branch in docs

* Updating references to /rails/blob/master & raiks/tree/master to point to main

* Don't return query cache enabled pools in the query cache executor

Follow up #41046.

If query cache is enabled for all connection pools, `pools` always
matches to `all_connection_pools`, returning `pools` has become
redundant.

* Remove trailing commas in advanced route constraints example

* Search for yarn.cmd and yarn.ps1 in bin/yarn

Follow-up to #40950.

On Windows, Yarn actually uses `yarn.cmd` and `yarn.ps1` for PowerShell.

* Run bin/yarn via Ruby

Windows cannot directly run shebang scripts, such as `bin/yarn`.
Therefore, run `bin/yarn` via Ruby.

Actually fixes #40942.
Fixes #41123.

* Allow to opt-out of `strict_loading` mode on a per-record base.

This is useful when strict loading is enabled application wide or on a
model level.

* Fix granular connection swapping when there are multiple abstract classes

Some applications maybe have multiple abstract classes in the
inheritance chain but only one of those abstract classes is the one we
want to switch connections on. Previously, multiple abstract class
inhertance would break `connected_to` and not switch models to the
correct connection context.

To fix this we added a boolean that is set on the class when a
connection is established so we can check for whether it's identified as
a `connection_class?`. This allows us to delete the `abstract_class?`
check, since you cannot establish a connection on a non-abstract class.

The existing tests were changed because they were not calling
`connects_to` and granular swapping won't work on classes that didn't
establish the connection. The issue in these tests will be prevented
when #40965 is merged.

Co-authored-by: John Crepezzi <john.crepezzi@gmail.com>

* Avoid testing Thor internals

Thor's `apply` method is responsible for fetching a template when given
a URL.  Therefore, assume that `apply` behaves correctly, and simply
test that `apply` is called correctly.

This avoids errors like https://buildkite.com/rails/rails/builds/74245#540ecdf1-58ea-470a-a397-09f675520eb9/1100-1109
resulting from erikhuda/thor@4ce38c5478.

* Fix the benchmark script to point to the main branch

* Resolve default annotation tags after config loads

`Rails::SourceAnnotationExtractor::Annotation.tags` may be modified by
app configuration.  Therefore, resolve default annotation tags after
loading the app configuration.

This fixes errors like https://buildkite.com/rails/rails/builds/74268#240d60bc-baa7-4b6e-ad21-b3172095f939/1083-1092
resulting from erikhuda/thor@0222fe52ed.

* Upgrade all the gems to make sure we are testing with the latest versions locally

* Don't bother checking if strings respond to string methods

The respond_to? calls here are checking if the unsafe method names, in
this case "gsub" and "sub", respond to those same methods. This is
nonsensical and unnecessary.

* Update name of input to fix typo

* `connected_to` shouldn't be called on the abstract class that not established connection

Fixed: https://github.com/rails/rails/issues/40559#issuecomment-752056106

When abstract class hasn't own connections, calling `AbstractClass.connection`
returns parent class's connection. We call `AbstractClass.connection.preventing_writes?`
expecting abstract class's state to be returned, but actually it is parent's one.

I think that it isn't expected behavior so I prevents call `connected_to` on the abstract
class that not established the connection.

* Add Webpacker to Guides list

Adds a link to the Webpacker guide (added in https://github.com/rails/rails/pull/40817) to the [guides list](https://guides.rubyonrails.org/) and "Guides Index" dropdown menu.

* Update documents.yaml

* Fix unintialized instance variable connection_class

This was throwing a warning when the test suite is run. Adding an
reader fixes the issue.

* Webpacker guide: remove Basecamp reference [docs]

As a Rails user, if you *don't* know who Basecamp is or their relationship to the Rails framework, then this sentence is confusing. Reworded to instead just refer to Rails defaults.

cc @rossta

* fix broken link

* Update webpacker.md

* Added the unless-block for continuity

* Added :status for continuity

* Removed line for continuity

* Added a new line after the include statement

* Connection specification now passes the "url" key to the adapter

If the "url" protocol is "jdbc", "http", or "https" the url option will
be passed to the adapter. Previously only urls with the "jdbc" prefix
were passed to the Active Record Adapter, others are assumed to be
adapter specification urls.

Fixes #41137.

* Support hash config for `structure_dump_flags` and `structure_load_flags` flags

    Now that Active Record supports multiple databases configuration
    we need a way to pass specific flags for dump/load databases since
    the options are not the same for different adapters.
    We can use in the original way:
    ```ruby
    ActiveRecord::Tasks::DatabaseTasks.structure_dump_flags = ['--no-defaults', '--skip-add-drop-table']
    #or
    ActiveRecord::Tasks::DatabaseTasks.structure_dump_flags = '--no-defaults --skip-add-drop-table'
    ```
    And also use it passing a hash, with one or more keys, where the key
    is the adapter
    ```ruby
    ActiveRecord::Tasks::DatabaseTasks.structure_dump_flags = {
      mysql2: ['--no-defaults', '--skip-add-drop-table'],
      postgres: '--no-tablespaces'
    }
    ```

* Update test docs in "contributing to Rails" guide

Updated guide to recommend `bin/test` and show examples of its use in different contexts.

Co-authored-by: Marivaldo Cavalheiro <marivaldo@gmail.com>

* Fix current_page? with kwargs on ruby3

Prevent raising an error when `options` are given as
kwargs, this is done by overriding `options` with kwargs
if `options` are `nil`; this implies that if both `options` and
kwargs are given, `options` takes precedence.

Fixes #41198

* `start_with?` allows multiple prefix values

* Fix code block in Webpacker Guide [ci skip]

Formatting fix: the example directory tree listing was bleeding into the
previous paragraph and had extraneous characters due to a missing
newline.

* Remove wrong usage for `arel_table` [ci skip]

This usage doesn't work properly (missing `where`, undefined `published`,
`arel_table` in the scope definition accidentally lose table alias).

* Restore ActiveStorage::Blob#find_signed

Rails 6.0 had a [public `find_signed` method][docs], but we changed it
to `find_signed!` in 31148cd6be.

This commit adds back `find_signed` alongside `find_signed!` to match
the corresponding [Active Record methods][].

[docs]: https://api.rubyonrails.org/v6.0.0/classes/ActiveStorage/Blob.html#method-c-find_signed
[Active Record methods]: https://github.com/rails/rails/blob/main/activerecord/lib/active_record/signed_id.rb#L42-L66

* Handle throwing in controller action in log subscriber

When throw was used in a controller action, and there is matching catch
around the request in a Rack middleware, then :exception won't be
present in the event payload.

This is because ActiveSupport::Notifications::Instrumenter.instrument
sets :exception in a rescue handler, but rescue is never called in a
throw/catch scenario:

  catch(:halt) do
    begin
      throw :halt
    rescue Exception => e
      puts "rescue" # never reached
    ensure
      puts "ensure"
    end
  end

Missing :exception was actually handled prior to Rails 6.1.0, but an
optimization updated the code to assume this was present. So this can be
considered a regression fix.

* Improve Fixture support for Active Storage (#41065)

* Improve Fixture support for Active Storage

Inspired by [76b33aa][], this commit extends the Active Storage
documentation to elaborate on how to declare fixtures.

In support of that, also introduce the `ActiveStorage::FixtureSet.blob`
method for injecting in-line [ActiveStorage::Blob][] attributes directly
into fixture YAML.

[76b33aa]: 76b33aa3d1
[ActiveStorage::Blob]: https://edgeapi.rubyonrails.org/classes/ActiveStorage/Blob.html

* Extra CR for style

* Two-space indention

* Explaining variable didn't explain, inline for style

Co-authored-by: David Heinemeier Hansson <david@loudthinking.com>

* Improve ActionText::FixtureSet documentation (#41062)

* Improve ActionText::FixtureSet documentation

Support for Action Text attachments in fixtures was added by [76b33aa][] and
released as part of [6.1.1][], but has not yet been documented.

This commit documents the `ActionText::FixtureSet` for the API
documentation, and mentions it in the Rails Guides pages.

[76b33aa]: 76b33aa3d1
[6.1.1]: https://github.com/rails/rails/releases/tag/v6.1.1

* Fix indention of comments

Co-authored-by: David Heinemeier Hansson <david@loudthinking.com>

* Fix Flaky ActiveStorage test (#41225)

Fixes a flaky Active Storage test introduced by [rails/rails#41065][],
and improves the documentation.

It seems that the test is covering the backwards compatibility of an
older interface for retrieving records through
`ActiveStorage::Record#find_signed!`. The test itself would pass
unpredictably. To isolate the failure and reproduce it consistently, a
see value was found after some trial and error:

```
SEED=59729 bin/test test/fixture_set_test.rb test/models/attachment_test.rb
```

This _used_ to pass consistently because [rails/rails][#41065]
introduced a call to `fixtures :all`, which introduces more variation in
the database's ID generation sequence. Without that line, `id` values
start at `1`, so the fact that calls to
`ActiveStorage::Attached::One#id` and `ActiveStorage::Blob#id` **both
return `1`** is purely coincidence.

The proposed resolution changes the test slightly. Prior to this change,
the identifier used during retrieval and verification fetched from
`@user.avatar.id`, where `@user.avatar` is an instance of
`ActiveStorage::Attached::One`. The verifier/retriever combination in
that test expected a signed identifier for an `ActiveStorage::Blob`
instance. The change involved retrieving an instance through
`@user.avatar.blob`.

To better emphasize how global the `fixtures :all` declaration is, move
it from the `test/fixture_set_test.rb` file to the `test/test_helper.rb`
file.

[rails/rails#41065]: https://github.com/rails/rails/pull/41065

* Fix doc: stylesheet_include_tag -> stylesheet_link_tag

* Remove reference to globalize gem

* Fix typo [ci skip]

* Add small improvements to the Webpacker guide

- fix typos like double spaces, accidental caps
- improve some HTML links by giving them a label
- etc

* Fixing delegated types example.

* Allow jobs to rescue all exceptions

Before this commit, only StandardError exceptions can be handled by
rescue_from handlers.

This changes the rescue clause to catch all Exception objects, allowing
rescue handlers to be defined for Exception classes not inheriting from
StandardError.

This means that rescue handlers that are rescuing Exceptions outside of
StandardError exceptions may rescue exceptions that were not being
rescued before this change.

Co-authored-by: Adrianna Chang <adrianna.chang@shopify.com>

* Guides: Missing erb tags for stylesheet_pack_tag [ci skip]

The section on needing to use `stylesheet_pack_tag` was lacking the erb
%'s.

I updated the markdown to actually show the helper being used with erb
as well as improve the wording of the sentence.

* Guides: Remove unneeded statement about stylesheet_pack_tag [ci skip]

* Update test names to match their behaviour

These tests were names `…creation_failure…` but there's no creation
failing in the tests themselves. Instead creation is succeeding, via
the `create_association` method which is added by the `has_one` relation.

I found these test names very confusing when reading this issue:
https://github.com/rails/rails/issues/13197
And the commit it links to: c6e10b0

The least we can do to make that issue less confusing is to start by
fixing these test names.
[ci skip]

* Remove SET NAMES, set collation using variable

Fixes malformed packet error that occurred with MariaDB client
connecting to RDS Aurora (MySQL 5.7) database.

* Update test helper to call parallelize according to fork support

* Show a warning when running no migration using SCOPE

When running a migration with `ENV["SCOPE"]` set returns a warning
if no migrations ran.
The message serves as a hint for the end-user to make sure he knows
that the migration have been filtered by `SCOPE`.

* Move ActiveStorage fixture hooks to on_load

In a test environment, rely on the loading of
`:active_support_test_case`.

Introduce the `:active_record_fixture_set` hook for the Active Storage
engine to listen for during the load process in a development
environment (like when running `db:fixtures:load`).

Since this commit moves the task-aware path resolution out of the block
that provided local variables, it recreates part of the fixture
directory path resolution logic.

* Improve ActiveRecord strict_loading documentation

Apply the same structure as the documentation of `validate` option by
starting the description with "when set to true". This implies, that
the value passed to the option should be a boolean.

* Remove legacy media=screen default from stylesheet_link_tag.

If the media attribute is omitted, the default for web browsers is "all", meaning that by default links apply to all media.

Before:

```ruby
> stylesheet_link_tag "style"
=> <link href="/assets/style.css" media="screen" rel="stylesheet" />
```

After:

```ruby
> stylesheet_link_tag "style"
=> <link href="/assets/style.css" rel="stylesheet" />

```

The current behavior is not going to change for existing applications.

For newly built applications, the media attribute is not going to be added by default. Which can be configured using the following:

```
Rails.application.config.action_view.stylesheet_media_default = false
```

* Do not eagerly load Request before initializers

Without those changes the configurations to ActionDispatch::Request
could not be applied in initializers.

* Change Request#media_type to return nil

When the request don't have a Content-Type header we were returning
an empty string instead of nil like Rack does.

* `ActionDispatch::Request#content_type` now returned Content-Type header as it is

* Disable rubocop suggestions

* Fix typo in the CHANGELOG

* Add config.action_view.stylesheet_media_default to baseline config

* Rename the config to make clear it is a boolean

* Add CHANGELOG entry for #41215

* Fix CI failure due to `app.config.action_view.delete(:apply_apply_stylesheet_media_default)`

https://buildkite.com/rails/rails/builds/74429#3de35026-a6dc-4f4c-b885-9b59e0c89b96/979-1036

* Fix deprecation message s/Rails 6.1 will return/Rails 7.0 will return/

`return_only_media_type_on_content_type` will be introduced in Rails 6.2
so the changing of returning Content-Type will happen in a future
version of Rails (probably 7.0).

* Revert "Merge pull request #41192 from kamipo/dont_return_pools"

This reverts commit 9d8ff32372, reversing
changes made to 9cde02ef5f.

Need to revert this so I can revert another PR.

* Revert "Merge pull request #41046 from eileencodes/dont-check-if-qc-is-enabled"

This reverts commit c97f1f195f, reversing
changes made to ac7851eb58.

We haven't quite tracked down why yet, but this change caused our API to
not use the query cache. Our API is Sinatra mixed with Rails. We install
the Exectutor in our API so it was installed. However, (some?)
production requests were showing 0 query cache hits.

jhawthorn found that we likely need this check because if we don't the
pools returned will be a different set. He'll send a test later today.

* Ensure test rake commands run immediately

Before this commit, Rails test Rake tasks only load the test files, and
the tests only run in an at_exit hook via minitest/autorun.

This prevents conditionally running tasks only when tests pass, or even
more simply in the right order. As a simple example, if you have:

task default: [:test, :rubocop]

The rubocop task will run after the test task loads the test files but
before the tests actually run.

This commit changes the test Rake tasks to shell out to the test runner
as a new process.

This diverges from previous behavior because now, any changes made in
the Rakefile or other code loaded by Rake won't be available to the
child process. However this brings the behavior of `rake test` closer to
the behavior of `rails test`.

Co-authored-by: Adrianna Chang <adrianna.chang@shopify.com>

* Fix typo

Co-authored-by: Haroon Ahmed <haroon.ahmed25@gmail.com>
Co-authored-by: Jonathan Hefner <jonathan@hefner.pro>
Co-authored-by: Gannon McGibbon <gannon.mcgibbon@gmail.com>
Co-authored-by: Rafael Mendonça França <rafael@franca.dev>
Co-authored-by: John Hawthorn <john@hawthorn.email>
Co-authored-by: Dinah Shi <dinahshi@github.com>
Co-authored-by: Santiago Bartesaghi <santib@hey.com>
Co-authored-by: Mike Rogers <me@mikerogers.io>
Co-authored-by: Ryuta Kamizono <kamipo@gmail.com>
Co-authored-by: Ryan Bigg <me@ryanbigg.com>
Co-authored-by: Jacopo <beschi.jacopo@gmail.com>
Co-authored-by: Guillaume Briday <guillaumebriday@gmail.com>
Co-authored-by: benhayehudi <bengreenberg@gmail.com>
Co-authored-by: wout@mick-wout.com <Wout>
Co-authored-by: Ayrton De Craene <hello@ayrton.be>
Co-authored-by: eileencodes <eileencodes@gmail.com>
Co-authored-by: John Crepezzi <john.crepezzi@gmail.com>
Co-authored-by: Chris Salzberg <chris@dejimata.com>
Co-authored-by: Tim Tilberg <ttilberg@gmail.com>
Co-authored-by: alpaca-tc <alpaca-tc@alpaca.tc>
Co-authored-by: Alex Ghiculescu <alex@tanda.co>
Co-authored-by: Xavier Noria <fxn@hashref.com>
Co-authored-by: ijlee2 <ijlee2@users.noreply.github.com>
Co-authored-by: Jon Bracy <jonbracy@gmail.com>
Co-authored-by: Gustavo Gonzalez <gustavo@gonzalez.guru>
Co-authored-by: Marivaldo Cavalheiro <marivaldo@gmail.com>
Co-authored-by: Chris Houhoulis <chris@chrishouhoulis.com>
Co-authored-by: Daniel Colson <daniel.colson@hey.com>
Co-authored-by: Janko Marohnić <janko.marohnic@gmail.com>
Co-authored-by: Sean Doyle <seanpdoyle@users.noreply.github.com>
Co-authored-by: André Luis Leal Cardoso Junior <andrehjr@gmail.com>
Co-authored-by: Youssef Boulkaid <yboulkaid@gmail.com>
Co-authored-by: Orhan Toy <toyorhan@gmail.com>
Co-authored-by: David Stosik <david.stosik+git-noreply@gmail.com>
Co-authored-by: Andrew Culver <andrew.culver@gmail.com>
Co-authored-by: Étienne Barrié <etienne.barrie@gmail.com>
Co-authored-by: Adrianna Chang <adrianna.chang@shopify.com>
Co-authored-by: Tony Drake <t27duck@gmail.com>
Co-authored-by: Sam Jewell <sam@bridge-u.com>
Co-authored-by: Robin Roestenburg <robin.roestenburg@4me.com>
Co-authored-by: Brandon Fish <brandon.j.fish@oracle.com>
Co-authored-by: Sean Doyle <sean.p.doyle24@gmail.com>
Co-authored-by: Cecile Veneziani <contact@cecilitse.org>
Co-authored-by: st0012 <stan001212@gmail.com>
2021-02-04 12:26:16 +01:00

719 lines
26 KiB
Ruby

# frozen_string_literal: true
require "generators/generators_test_helper"
require "rails/generators/rails/scaffold/scaffold_generator"
class ScaffoldGeneratorTest < Rails::Generators::TestCase
include GeneratorsTestHelper
arguments %w(product_line title:string approved:boolean product:belongs_to user:references)
setup :copy_routes
def test_scaffold_on_invoke
run_generator
# Model
assert_file "app/models/product_line.rb", /class ProductLine < ApplicationRecord/
assert_file "test/models/product_line_test.rb", /class ProductLineTest < ActiveSupport::TestCase/
assert_file "test/fixtures/product_lines.yml"
assert_migration "db/migrate/create_product_lines.rb", /belongs_to :product/
assert_migration "db/migrate/create_product_lines.rb", /boolean :approved/
assert_migration "db/migrate/create_product_lines.rb", /references :user/
# Route
assert_file "config/routes.rb" do |route|
assert_match(/resources :product_lines$/, route)
end
# Controller
assert_file "app/controllers/product_lines_controller.rb" do |content|
assert_match(/class ProductLinesController < ApplicationController/, content)
assert_instance_method :index, content do |m|
assert_match(/@product_lines = ProductLine\.all/, m)
end
assert_instance_method :show, content
assert_instance_method :new, content do |m|
assert_match(/@product_line = ProductLine\.new/, m)
end
assert_instance_method :edit, content
assert_instance_method :create, content do |m|
assert_match(/@product_line = ProductLine\.new\(product_line_params\)/, m)
assert_match(/@product_line\.save/, m)
end
assert_instance_method :update, content do |m|
assert_match(/@product_line\.update\(product_line_params\)/, m)
end
assert_instance_method :destroy, content do |m|
assert_match(/@product_line\.destroy/, m)
end
assert_instance_method :set_product_line, content do |m|
assert_match(/@product_line = ProductLine\.find\(params\[:id\]\)/, m)
end
end
assert_file "test/controllers/product_lines_controller_test.rb" do |test|
assert_match(/class ProductLinesControllerTest < ActionDispatch::IntegrationTest/, test)
assert_match(/post product_lines_url, params: \{ product_line: \{ approved: @product_line\.approved, product_id: @product_line\.product_id, title: @product_line\.title, user_id: @product_line\.user_id \} \}/, test)
assert_match(/patch product_line_url\(@product_line\), params: \{ product_line: \{ approved: @product_line\.approved, product_id: @product_line\.product_id, title: @product_line\.title, user_id: @product_line\.user_id \} \}/, test)
end
# System tests
assert_file "test/system/product_lines_test.rb" do |test|
assert_match(/class ProductLinesTest < ApplicationSystemTestCase/, test)
assert_match(/visit product_lines_url/, test)
assert_match(/fill_in "Title", with: @product_line\.title/, test)
assert_match(/check "Approved" if @product_line\.approved/, test)
assert_match(/assert_text "Product line was successfully updated"/, test)
end
# Views
assert_no_file "app/views/layouts/product_lines.html.erb"
%w(index show).each do |view|
assert_file "app/views/product_lines/#{view}.html.erb"
end
%w(edit new).each do |view|
assert_file "app/views/product_lines/#{view}.html.erb", /render "form", product_line: @product_line/
end
assert_file "app/views/product_lines/_form.html.erb" do |test|
assert_match "product_line", test
assert_no_match "@product_line", test
end
# Helpers
assert_file "app/helpers/product_lines_helper.rb"
# Assets
assert_file "app/assets/stylesheets/scaffold.css"
assert_file "app/assets/stylesheets/product_lines.css"
end
def test_api_scaffold_on_invoke
run_generator %w(product_line title:string product:belongs_to user:references --api --no-template-engine --no-helper --no-assets)
# Model
assert_file "app/models/product_line.rb", /class ProductLine < ApplicationRecord/
assert_file "test/models/product_line_test.rb", /class ProductLineTest < ActiveSupport::TestCase/
assert_file "test/fixtures/product_lines.yml"
assert_migration "db/migrate/create_product_lines.rb", /belongs_to :product/
assert_migration "db/migrate/create_product_lines.rb", /references :user/
# Route
assert_file "config/routes.rb" do |route|
assert_match(/resources :product_lines$/, route)
end
# Controller
assert_file "app/controllers/product_lines_controller.rb" do |content|
assert_match(/class ProductLinesController < ApplicationController/, content)
assert_no_match(/respond_to/, content)
assert_match(/before_action :set_product_line, only: %i\[ show update destroy \]/, content)
assert_instance_method :index, content do |m|
assert_match(/@product_lines = ProductLine\.all/, m)
assert_match(/render json: @product_lines/, m)
end
assert_instance_method :show, content do |m|
assert_match(/render json: @product_line/, m)
end
assert_instance_method :create, content do |m|
assert_match(/@product_line = ProductLine\.new\(product_line_params\)/, m)
assert_match(/@product_line\.save/, m)
assert_match(/@product_line\.errors/, m)
end
assert_instance_method :update, content do |m|
assert_match(/@product_line\.update\(product_line_params\)/, m)
assert_match(/@product_line\.errors/, m)
end
assert_instance_method :destroy, content do |m|
assert_match(/@product_line\.destroy/, m)
end
end
assert_file "test/controllers/product_lines_controller_test.rb" do |test|
assert_match(/class ProductLinesControllerTest < ActionDispatch::IntegrationTest/, test)
assert_match(/post product_lines_url, params: \{ product_line: \{ product_id: @product_line\.product_id, title: @product_line\.title, user_id: @product_line\.user_id \} \}/, test)
assert_match(/patch product_line_url\(@product_line\), params: \{ product_line: \{ product_id: @product_line\.product_id, title: @product_line\.title, user_id: @product_line\.user_id \} \}/, test)
assert_no_match(/assert_redirected_to/, test)
end
# System tests
assert_no_file "test/system/product_lines_test.rb"
# Views
assert_no_file "app/views/layouts/product_lines.html.erb"
%w(index show new edit _form).each do |view|
assert_no_file "app/views/product_lines/#{view}.html.erb"
end
# Helpers
assert_no_file "app/helpers/product_lines_helper.rb"
# Assets
assert_no_file "app/assets/stylesheets/scaffold.css"
assert_no_file "app/assets/stylesheets/product_lines.css"
end
def test_functional_tests_without_attributes
run_generator ["product_line"]
assert_file "test/controllers/product_lines_controller_test.rb" do |content|
assert_match(/class ProductLinesControllerTest < ActionDispatch::IntegrationTest/, content)
assert_match(/test "should get index"/, content)
assert_match(/post product_lines_url, params: \{ product_line: \{ \} \}/, content)
assert_match(/patch product_line_url\(@product_line\), params: \{ product_line: \{ \} \}/, content)
end
end
def test_system_tests_without_attributes
run_generator ["product_line"]
assert_file "test/system/product_lines_test.rb" do |content|
assert_match(/class ProductLinesTest < ApplicationSystemTestCase/, content)
assert_match(/test "visiting the index"/, content)
assert_no_match(/fill_in/, content)
end
end
def test_scaffold_on_revoke
run_generator
run_generator ["product_line"], behavior: :revoke
# Model
assert_no_file "app/models/product_line.rb"
assert_no_file "test/models/product_line_test.rb"
assert_no_file "test/fixtures/product_lines.yml"
assert_no_migration "db/migrate/create_product_lines.rb"
# Route
assert_file "config/routes.rb" do |route|
assert_no_match(/resources :product_lines$/, route)
end
# Controller
assert_no_file "app/controllers/product_lines_controller.rb"
assert_no_file "test/controllers/product_lines_controller_test.rb"
# System tests
assert_no_file "test/system/product_lines_test.rb"
# Views
assert_no_file "app/views/product_lines"
assert_no_file "app/views/layouts/product_lines.html.erb"
# Helpers
assert_no_file "app/helpers/product_lines_helper.rb"
# Assets
assert_file "app/assets/stylesheets/scaffold.css", /.scaffold_record/
assert_no_file "app/assets/stylesheets/product_lines.css"
end
def test_scaffold_with_namespace_on_invoke
run_generator [ "admin/role", "name:string", "description:string" ]
# Model
assert_file "app/models/admin.rb", /module Admin/
assert_file "app/models/admin/role.rb", /class Admin::Role < ApplicationRecord/
assert_file "test/models/admin/role_test.rb", /class Admin::RoleTest < ActiveSupport::TestCase/
assert_file "test/fixtures/admin/roles.yml"
assert_migration "db/migrate/create_admin_roles.rb"
# Route
assert_file "config/routes.rb" do |route|
assert_match(/^ namespace :admin do\n resources :roles\n end$/, route)
end
# Controller
assert_file "app/controllers/admin/roles_controller.rb" do |content|
assert_match(/class Admin::RolesController < ApplicationController/, content)
assert_instance_method :index, content do |m|
assert_match(/@admin_roles = Admin::Role\.all/, m)
end
assert_instance_method :show, content
assert_instance_method :new, content do |m|
assert_match(/@admin_role = Admin::Role\.new/, m)
end
assert_instance_method :edit, content
assert_instance_method :create, content do |m|
assert_match(/@admin_role = Admin::Role\.new\(admin_role_params\)/, m)
assert_match(/@admin_role\.save/, m)
end
assert_instance_method :update, content do |m|
assert_match(/@admin_role\.update\(admin_role_params\)/, m)
end
assert_instance_method :destroy, content do |m|
assert_match(/@admin_role\.destroy/, m)
end
assert_instance_method :set_admin_role, content do |m|
assert_match(/@admin_role = Admin::Role\.find\(params\[:id\]\)/, m)
end
end
assert_file "test/controllers/admin/roles_controller_test.rb",
/class Admin::RolesControllerTest < ActionDispatch::IntegrationTest/
assert_file "test/system/admin/roles_test.rb",
/class Admin::RolesTest < ApplicationSystemTestCase/
# Views
assert_file "app/views/admin/roles/index.html.erb" do |content|
assert_match(%("New role", new_admin_role_path), content)
end
%w(edit new show _form).each do |view|
assert_file "app/views/admin/roles/#{view}.html.erb"
end
assert_no_file "app/views/layouts/admin/roles.html.erb"
# Helpers
assert_file "app/helpers/admin/roles_helper.rb"
# Assets
assert_file "app/assets/stylesheets/scaffold.css", /.scaffold_record/
assert_file "app/assets/stylesheets/admin/roles.css"
end
def test_scaffold_with_namespace_on_revoke
run_generator [ "admin/role", "name:string", "description:string" ]
run_generator [ "admin/role" ], behavior: :revoke
# Model
assert_file "app/models/admin.rb" # ( should not be remove )
assert_no_file "app/models/admin/role.rb"
assert_no_file "test/models/admin/role_test.rb"
assert_no_file "test/fixtures/admin/roles.yml"
assert_no_migration "db/migrate/create_admin_roles.rb"
# Route
assert_file "config/routes.rb" do |route|
assert_no_match(/namespace :admin do resources :roles end$/, route)
end
# Controller
assert_no_file "app/controllers/admin/roles_controller.rb"
assert_no_file "test/controllers/admin/roles_controller_test.rb"
# System tests
assert_no_file "test/system/admin/roles_test.rb"
# Views
assert_no_file "app/views/admin/roles"
assert_no_file "app/views/layouts/admin/roles.html.erb"
# Helpers
assert_no_file "app/helpers/admin/roles_helper.rb"
# Assets
assert_file "app/assets/stylesheets/scaffold.css"
assert_no_file "app/assets/stylesheets/admin/roles.css"
end
def test_scaffold_generator_on_revoke_does_not_mutilate_legacy_map_parameter
run_generator
# Add a |map| parameter to the routes block manually
route_path = File.expand_path("config/routes.rb", destination_root)
content = File.read(route_path).gsub(/\.routes\.draw do/) do |match|
"#{match} |map|"
end
File.write(route_path, content)
run_generator ["product_line"], behavior: :revoke
assert_file "config/routes.rb", /\.routes\.draw do\s*\|map\|\s*$/
end
def test_scaffold_generator_on_revoke_does_not_mutilate_routes
run_generator
route_path = File.expand_path("config/routes.rb", destination_root)
content = File.read(route_path)
# Remove all of the comments and blank lines from the routes file
content.gsub!(/^ \#.*\n/, "")
content.gsub!(/^\n/, "")
File.write(route_path, content)
assert_file "config/routes.rb", /\.routes\.draw do\n resources :product_lines\nend\n\z/
run_generator ["product_line"], behavior: :revoke
assert_file "config/routes.rb", /\.routes\.draw do\nend\n\z/
end
def test_scaffold_generator_ignores_commented_routes
run_generator ["product"]
assert_file "config/routes.rb", /\.routes\.draw do\n resources :products\n/
end
def test_scaffold_generator_no_assets_with_switch_no_assets
run_generator [ "posts", "--no-assets" ]
assert_no_file "app/assets/stylesheets/scaffold.css"
assert_no_file "app/assets/stylesheets/posts.css"
end
def test_scaffold_generator_no_assets_with_switch_assets_false
run_generator [ "posts", "--assets=false" ]
assert_no_file "app/assets/stylesheets/scaffold.css"
assert_no_file "app/assets/stylesheets/posts.css"
end
def test_scaffold_generator_no_scaffold_stylesheet_with_switch_no_scaffold_stylesheet
run_generator [ "posts", "--no-scaffold-stylesheet" ]
assert_no_file "app/assets/stylesheets/scaffold.css"
assert_file "app/assets/stylesheets/posts.css"
end
def test_scaffold_generator_no_scaffold_stylesheet_with_switch_scaffold_stylesheet_false
run_generator [ "posts", "--scaffold-stylesheet=false" ]
assert_no_file "app/assets/stylesheets/scaffold.css"
assert_file "app/assets/stylesheets/posts.css"
end
def test_scaffold_generator_with_switch_resource_route_false
run_generator [ "posts", "--resource-route=false" ]
assert_file "config/routes.rb" do |route|
assert_no_match(/resources :posts$/, route)
end
end
def test_scaffold_generator_no_helper_with_switch_no_helper
output = run_generator [ "posts", "--no-helper" ]
assert_no_match(/error/, output)
assert_no_file "app/helpers/posts_helper.rb"
end
def test_scaffold_generator_no_helper_with_switch_helper_false
output = run_generator [ "posts", "--helper=false" ]
assert_no_match(/error/, output)
assert_no_file "app/helpers/posts_helper.rb"
end
def test_scaffold_generator_no_stylesheets
run_generator [ "posts", "--no-stylesheets" ]
assert_no_file "app/assets/stylesheets/scaffold.css"
assert_no_file "app/assets/stylesheets/posts.css"
end
def test_scaffold_generator_outputs_error_message_on_missing_attribute_type
run_generator ["post", "title", "body:text", "author"]
assert_migration "db/migrate/create_posts.rb" do |m|
assert_method :change, m do |up|
assert_match(/t\.string :title/, up)
assert_match(/t\.text :body/, up)
assert_match(/t\.string :author/, up)
end
end
end
def test_scaffold_generator_belongs_to_and_references
run_generator ["account", "name", "currency:belongs_to", "user:references"]
assert_file "app/models/account.rb", /belongs_to :currency/
assert_migration "db/migrate/create_accounts.rb" do |m|
assert_method :change, m do |up|
assert_match(/t\.string :name/, up)
assert_match(/t\.belongs_to :currency/, up)
end
end
assert_file "app/controllers/accounts_controller.rb" do |content|
assert_instance_method :account_params, content do |m|
assert_match(/permit\(:name, :currency_id, :user_id\)/, m)
end
end
assert_file "app/views/accounts/_form.html.erb" do |content|
assert_match(/^\W{4}<%= form\.text_field :name %>/, content)
assert_match(/^\W{4}<%= form\.text_field :currency_id %>/, content)
end
assert_file "app/views/accounts/index.html.erb" do |content|
assert_match(/^\W{2}<%= render @accounts %>/, content)
end
assert_file "app/views/accounts/show.html.erb" do |content|
assert_match(/<%= render @account %>/, content)
assert_match(/link_to "Edit this account"/, content)
assert_match(/button_to "Destroy this account"/, content)
assert_match(/link_to "Back to accounts"/, content)
end
end
def test_scaffold_generator_attachments
run_generator ["message", "video:attachment", "photos:attachments", "images:attachments"]
assert_file "app/models/message.rb", /has_one_attached :video/
assert_file "app/models/message.rb", /has_many_attached :photos/
assert_file "app/controllers/messages_controller.rb" do |content|
assert_instance_method :message_params, content do |m|
assert_match(/permit\(:video, photos: \[\], images: \[\]\)/, m)
end
end
assert_file "app/views/messages/_form.html.erb" do |content|
assert_match(/^\W{4}<%= form\.file_field :video %>/, content)
assert_match(/^\W{4}<%= form\.file_field :photos, multiple: true %>/, content)
end
assert_file "app/views/messages/_message.html.erb" do |content|
assert_match(/^\W{4}<%= link_to message\.video\.filename, message\.video if message\.video\.attached\? %>/, content)
assert_match(/^\W{6}<div><%= link_to photo\.filename, photo %>/, content)
end
assert_file "test/system/messages_test.rb" do |content|
assert_no_match(/fill_in "Video"/, content)
assert_no_match(/fill_in "Photos"/, content)
end
end
def test_scaffold_generator_rich_text
run_generator ["message", "content:rich_text"]
assert_file "app/models/message.rb", /rich_text :content/
assert_file "app/controllers/messages_controller.rb" do |content|
assert_instance_method :message_params, content do |m|
assert_match(/permit\(:content\)/, m)
end
end
assert_file "app/views/messages/_form.html.erb" do |content|
assert_match(/^\W{4}<%= form\.rich_text_area :content %>/, content)
end
assert_file "test/system/messages_test.rb" do |content|
assert_no_match(/fill_in "Content"/, content)
end
end
def test_scaffold_generator_multi_db_abstract_class
with_database_configuration do
run_generator ["posts", "--database=secondary"]
assert_migration "db/secondary_migrate/create_posts.rb"
assert_file "app/models/secondary_record.rb" do |content|
assert_match(/class SecondaryRecord < ApplicationRecord/, content)
assert_match(/connects_to database: { writing: :secondary }/, content)
assert_match(/self.abstract_class = true/, content)
end
end
end
def test_scaffold_generator_database_with_aliases
with_database_configuration do
run_generator ["posts", "--db=secondary"]
assert_migration "db/secondary_migrate/create_posts.rb"
end
end
def test_scaffold_generator_password_digest
run_generator ["user", "name", "password:digest"]
assert_file "app/models/user.rb", /has_secure_password/
assert_migration "db/migrate/create_users.rb" do |m|
assert_method :change, m do |up|
assert_match(/t\.string :name/, up)
assert_match(/t\.string :password_digest/, up)
end
end
assert_file "app/controllers/users_controller.rb" do |content|
assert_instance_method :user_params, content do |m|
assert_match(/permit\(:name, :password, :password_confirmation\)/, m)
end
end
assert_file "app/views/users/_form.html.erb" do |content|
assert_match(/<%= form\.password_field :password %>/, content)
assert_match(/<%= form\.password_field :password_confirmation %>/, content)
end
assert_file "app/views/users/index.html.erb" do |content|
assert_no_match(/password/, content)
end
assert_file "app/views/users/show.html.erb" do |content|
assert_no_match(/password/, content)
end
assert_file "test/controllers/users_controller_test.rb" do |content|
assert_match(/password: 'secret'/, content)
assert_match(/password_confirmation: 'secret'/, content)
end
assert_file "test/system/users_test.rb" do |content|
assert_match(/fill_in "Password", with: 'secret'/, content)
assert_match(/fill_in "Password confirmation", with: 'secret'/, content)
end
assert_file "test/fixtures/users.yml" do |content|
assert_match(/password_digest: <%= BCrypt::Password.create\('secret'\) %>/, content)
end
end
def test_scaffold_tests_pass_by_default_inside_mountable_engine
Dir.chdir(destination_root) { `bundle exec rails plugin new bukkits --mountable` }
engine_path = File.join(destination_root, "bukkits")
Dir.chdir(engine_path) do
quietly do
`bin/rails g scaffold User name:string age:integer;
bin/rails db:migrate`
end
assert_match(/8 runs, 10 assertions, 0 failures, 0 errors/, `bin/rails test 2>&1`)
end
end
def test_scaffold_tests_pass_by_default_inside_namespaced_mountable_engine
Dir.chdir(destination_root) { `bundle exec rails plugin new bukkits-admin --mountable` }
engine_path = File.join(destination_root, "bukkits-admin")
Dir.chdir(engine_path) do
quietly do
`bin/rails g scaffold User name:string age:integer;
bin/rails db:migrate`
end
assert_file "bukkits-admin/app/controllers/bukkits/admin/users_controller.rb" do |content|
assert_match(/module Bukkits::Admin/, content)
assert_match(/class UsersController < ApplicationController/, content)
end
assert_match(/8 runs, 10 assertions, 0 failures, 0 errors/, `bin/rails test 2>&1`)
end
end
def test_scaffold_tests_pass_by_default_inside_full_engine
Dir.chdir(destination_root) { `bundle exec rails plugin new bukkits --full` }
engine_path = File.join(destination_root, "bukkits")
Dir.chdir(engine_path) do
quietly do
`bin/rails g scaffold User name:string age:integer;
bin/rails db:migrate`
end
assert_match(/8 runs, 10 assertions, 0 failures, 0 errors/, `bin/rails test 2>&1`)
end
end
def test_scaffold_tests_pass_by_default_inside_api_mountable_engine
Dir.chdir(destination_root) { `bundle exec rails plugin new bukkits --mountable --api` }
engine_path = File.join(destination_root, "bukkits")
Dir.chdir(engine_path) do
quietly do
`bin/rails g scaffold User name:string age:integer;
bin/rails db:migrate`
end
assert_match(/6 runs, 8 assertions, 0 failures, 0 errors/, `bin/rails test 2>&1`)
end
end
def test_scaffold_tests_pass_by_default_inside_api_full_engine
Dir.chdir(destination_root) { `bundle exec rails plugin new bukkits --full --api` }
engine_path = File.join(destination_root, "bukkits")
Dir.chdir(engine_path) do
quietly do
`bin/rails g scaffold User name:string age:integer;
bin/rails db:migrate`
end
assert_match(/6 runs, 8 assertions, 0 failures, 0 errors/, `bin/rails test 2>&1`)
end
end
def test_scaffold_on_invoke_inside_mountable_engine
Dir.chdir(destination_root) { `bundle exec rails plugin new bukkits --mountable` }
engine_path = File.join(destination_root, "bukkits")
Dir.chdir(engine_path) do
quietly { `bin/rails generate scaffold User name:string age:integer` }
assert File.exist?("app/models/bukkits/user.rb")
assert File.exist?("test/models/bukkits/user_test.rb")
assert File.exist?("test/fixtures/bukkits/users.yml")
assert File.exist?("app/controllers/bukkits/users_controller.rb")
assert File.exist?("test/controllers/bukkits/users_controller_test.rb")
assert File.exist?("test/system/bukkits/users_test.rb")
assert File.exist?("app/views/bukkits/users/index.html.erb")
assert File.exist?("app/views/bukkits/users/edit.html.erb")
assert File.exist?("app/views/bukkits/users/show.html.erb")
assert File.exist?("app/views/bukkits/users/new.html.erb")
assert File.exist?("app/views/bukkits/users/_form.html.erb")
assert File.exist?("app/helpers/bukkits/users_helper.rb")
assert File.exist?("app/assets/stylesheets/bukkits/users.css")
end
end
def test_scaffold_on_revoke_inside_mountable_engine
Dir.chdir(destination_root) { `bundle exec rails plugin new bukkits --mountable` }
engine_path = File.join(destination_root, "bukkits")
Dir.chdir(engine_path) do
quietly { `bin/rails generate scaffold User name:string age:integer` }
quietly { `bin/rails destroy scaffold User` }
assert_not File.exist?("app/models/bukkits/user.rb")
assert_not File.exist?("test/models/bukkits/user_test.rb")
assert_not File.exist?("test/fixtures/bukkits/users.yml")
assert_not File.exist?("app/controllers/bukkits/users_controller.rb")
assert_not File.exist?("test/controllers/bukkits/users_controller_test.rb")
assert_not File.exist?("test/system/bukkits/users_test.rb")
assert_not File.exist?("app/views/bukkits/users/index.html.erb")
assert_not File.exist?("app/views/bukkits/users/edit.html.erb")
assert_not File.exist?("app/views/bukkits/users/show.html.erb")
assert_not File.exist?("app/views/bukkits/users/new.html.erb")
assert_not File.exist?("app/views/bukkits/users/_form.html.erb")
assert_not File.exist?("app/helpers/bukkits/users_helper.rb")
assert_not File.exist?("app/assets/stylesheets/bukkits/users.css")
end
end
end