diff options
Diffstat (limited to 'railties')
28 files changed, 845 insertions, 91 deletions
diff --git a/railties/CHANGELOG.md b/railties/CHANGELOG.md index 3813ef7909..9404c18f57 100644 --- a/railties/CHANGELOG.md +++ b/railties/CHANGELOG.md @@ -1,15 +1,48 @@ +* Move `secret_key_base` from `config/initializers/secret_token.rb` + to `config/secrets.yml`. + + `secret_key_base` is now saved in `Rails.application.secrets.secret_key_base` + and it fallbacks to the value of `config.secret_key_base` when it is not + present in `config/secrets.yml`. + + `config/initializers/secret_token.rb` is not generated by default + in new applications. + + *Guillermo Iguaran* + +* Generate a new `secrets.yml` file in the `config` folder for new + applications. By default, this file contains the application's `secret_key_base`, + but it could also be used to store other secrets such as access keys for external + APIs. + + The secrets added to this file will be accessible via `Rails.application.secrets`. + For example, with the following `secrets.yml`: + + development: + secret_key_base: 3b7cd727ee24e8444053437c36cc66c3 + some_api_key: SOMEKEY + + `Rails.application.secrets.some_api_key` will return `SOMEKEY` in the development + environment. + + *Guillermo Iguaran* + +* Add `ENV['DATABASE_URL']` support in `rails dbconsole`. Fixes #13320. + + *Huiming Teo* + * Add `Application#message_verifier` method to return a message verifier. This verifier can be used to generate and verify signed messages in the application. - message = Rails.application.message_verifier('salt').generate('my sensible data') - Rails.application.message_verifier('salt').verify(message) + message = Rails.application.message_verifier(:sensitive_data).generate('my sensible data') + Rails.application.message_verifier(:sensitive_data).verify(message) # => 'my sensible data' It is recommended not to use the same verifier for different things, so you can get different verifiers passing the name argument. - message = Rails.application.message_verifier('cookies').generate('my sensible cookie data') + message = Rails.application.message_verifier(:cookies).generate('my sensible cookie data') See the `ActiveSupport::MessageVerifier` documentation for more information. diff --git a/railties/lib/rails.rb b/railties/lib/rails.rb index ea82327365..be7570a5ba 100644 --- a/railties/lib/rails.rb +++ b/railties/lib/rails.rb @@ -25,6 +25,7 @@ module Rails autoload :Info autoload :InfoController + autoload :MailersController autoload :WelcomeController class << self diff --git a/railties/lib/rails/application.rb b/railties/lib/rails/application.rb index 06acb4c877..5b20c178eb 100644 --- a/railties/lib/rails/application.rb +++ b/railties/lib/rails/application.rb @@ -170,18 +170,18 @@ module Rails # # ==== Parameters # - # * +salt+ - the salt that will be used to generate the secret key of the verifier. + # * +verifier_name+ - the name of the message verifier. # # ==== Examples # - # message = Rails.application.message_verifier('salt').generate('my sensible data') - # Rails.application.message_verifier('salt').verify(message) + # message = Rails.application.message_verifier('sensitive_data').generate('my sensible data') + # Rails.application.message_verifier('sensitive_data').verify(message) # # => 'my sensible data' # # See the +ActiveSupport::MessageVerifier+ documentation for more information. - def message_verifier(salt) - @message_verifiers[salt] ||= begin - secret = key_generator.generate_key(salt) + def message_verifier(verifier_name) + @message_verifiers[verifier_name] ||= begin + secret = key_generator.generate_key(verifier_name.to_s) ActiveSupport::MessageVerifier.new(secret) end end diff --git a/railties/lib/rails/application/finisher.rb b/railties/lib/rails/application/finisher.rb index 7a1bb1e25c..5b8509b2e9 100644 --- a/railties/lib/rails/application/finisher.rb +++ b/railties/lib/rails/application/finisher.rb @@ -22,6 +22,8 @@ module Rails initializer :add_builtin_route do |app| if Rails.env.development? app.routes.append do + get '/rails/mailers' => "rails/mailers#index" + get '/rails/mailers/*path' => "rails/mailers#preview" get '/rails/info/properties' => "rails/info#properties" get '/rails/info/routes' => "rails/info#routes" get '/rails/info' => "rails/info#index" diff --git a/railties/lib/rails/application_controller.rb b/railties/lib/rails/application_controller.rb new file mode 100644 index 0000000000..9a29ec21cf --- /dev/null +++ b/railties/lib/rails/application_controller.rb @@ -0,0 +1,16 @@ +class Rails::ApplicationController < ActionController::Base # :nodoc: + self.view_paths = File.expand_path('../templates', __FILE__) + layout 'application' + + protected + + def require_local! + unless local_request? + render text: '<p>For security purposes, this information is only available to local requests.</p>', status: :forbidden + end + end + + def local_request? + Rails.application.config.consider_all_requests_local || request.local? + end +end diff --git a/railties/lib/rails/commands/dbconsole.rb b/railties/lib/rails/commands/dbconsole.rb index 3e4cc787c4..847447fdad 100644 --- a/railties/lib/rails/commands/dbconsole.rb +++ b/railties/lib/rails/commands/dbconsole.rb @@ -81,14 +81,11 @@ module Rails def config @config ||= begin - cfg = begin - YAML.load(ERB.new(IO.read("config/database.yml")).result) - rescue SyntaxError, StandardError - require APP_PATH - Rails.application.config.database_configuration - end - - cfg[environment] || abort("No database is configured for the environment '#{environment}'") + require APP_PATH + ActiveRecord::ConnectionAdapters::ConnectionSpecification::Resolver.new( + ENV['DATABASE_URL'], + (Rails.application.config.database_configuration || {}) + ).spec.config.stringify_keys end end diff --git a/railties/lib/rails/commands/runner.rb b/railties/lib/rails/commands/runner.rb index dd2ee5639e..3a71f8d3f8 100644 --- a/railties/lib/rails/commands/runner.rb +++ b/railties/lib/rails/commands/runner.rb @@ -9,7 +9,7 @@ if ARGV.first.nil? end ARGV.clone.options do |opts| - opts.banner = "Usage: rails runner [options] ('Some.ruby(code)' or a filename)" + opts.banner = "Usage: rails runner [options] [<'Some.ruby(code)'> | <filename.rb>]" opts.separator "" @@ -22,14 +22,23 @@ ARGV.clone.options do |opts| opts.on("-h", "--help", "Show this help message.") { $stdout.puts opts; exit } + opts.separator "" + opts.separator "Examples: " + + opts.separator " rails runner 'puts Rails.env'" + opts.separator " This runs the code `puts Rails.env` after loading the app" + opts.separator "" + opts.separator " rails runner path/to/filename.rb" + opts.separator " This runs the Ruby file located at `path/to/filename.rb` after loading the app" + if RbConfig::CONFIG['host_os'] !~ /mswin|mingw/ opts.separator "" opts.separator "You can also use runner as a shebang line for your executables:" - opts.separator "-------------------------------------------------------------" - opts.separator "#!/usr/bin/env #{File.expand_path($0)} runner" + opts.separator " -------------------------------------------------------------" + opts.separator " #!/usr/bin/env #{File.expand_path($0)} runner" opts.separator "" - opts.separator "Product.all.each { |p| p.price *= 2 ; p.save! }" - opts.separator "-------------------------------------------------------------" + opts.separator " Product.all.each { |p| p.price *= 2 ; p.save! }" + opts.separator " -------------------------------------------------------------" end opts.order! { |o| code_or_file ||= o } rescue retry diff --git a/railties/lib/rails/generators/base.rb b/railties/lib/rails/generators/base.rb index cf33b13fd8..67bab96a22 100644 --- a/railties/lib/rails/generators/base.rb +++ b/railties/lib/rails/generators/base.rb @@ -296,7 +296,7 @@ module Rails end end - # Return the default value for the option name given doing a lookup in + # Returns the default value for the option name given doing a lookup in # Rails::Generators.options. def self.default_value_for_option(name, options) default_for_option(Rails::Generators.options, name, options, options[:default]) diff --git a/railties/lib/rails/generators/rails/app/templates/config/secrets.yml b/railties/lib/rails/generators/rails/app/templates/config/secrets.yml index 50c1d1d8c7..b32e4bf2a6 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/secrets.yml +++ b/railties/lib/rails/generators/rails/app/templates/config/secrets.yml @@ -16,5 +16,11 @@ development: test: secret_key_base: <%= app_secret %> +# This YAML file is processed by ERB first (as others). In particular the +# production environment can set the secret via an environment variable +# this way: +# +# secret_key_base: <%%= ENV['SECRET_KEY_BASE'] %> +# production: secret_key_base: <%= app_secret %> diff --git a/railties/lib/rails/generators/test_unit/mailer/mailer_generator.rb b/railties/lib/rails/generators/test_unit/mailer/mailer_generator.rb index 3334b189bf..85dee1a066 100644 --- a/railties/lib/rails/generators/test_unit/mailer/mailer_generator.rb +++ b/railties/lib/rails/generators/test_unit/mailer/mailer_generator.rb @@ -4,11 +4,18 @@ module TestUnit # :nodoc: module Generators # :nodoc: class MailerGenerator < Base # :nodoc: argument :actions, type: :array, default: [], banner: "method method" - check_class_collision suffix: "Test" + + def check_class_collision + class_collisions "#{class_name}Test", "#{class_name}Preview" + end def create_test_files template "functional_test.rb", File.join('test/mailers', class_path, "#{file_name}_test.rb") end + + def create_preview_files + template "preview.rb", File.join('test/mailers/previews', class_path, "#{file_name}_preview.rb") + end end end end diff --git a/railties/lib/rails/generators/test_unit/mailer/templates/preview.rb b/railties/lib/rails/generators/test_unit/mailer/templates/preview.rb new file mode 100644 index 0000000000..ac14644145 --- /dev/null +++ b/railties/lib/rails/generators/test_unit/mailer/templates/preview.rb @@ -0,0 +1,11 @@ +<% module_namespacing do -%> +class <%= class_name %>Preview < ActionMailer::Preview +<% actions.each do |action| -%> + + def <%= action %> + <%= class_name %>.<%= action %> + end +<% end -%> + +end +<% end -%> diff --git a/railties/lib/rails/info_controller.rb b/railties/lib/rails/info_controller.rb index 85ea11b4e7..908c4ce65e 100644 --- a/railties/lib/rails/info_controller.rb +++ b/railties/lib/rails/info_controller.rb @@ -1,9 +1,9 @@ +require 'rails/application_controller' require 'action_dispatch/routing/inspector' -class Rails::InfoController < ActionController::Base # :nodoc: - self.view_paths = File.expand_path('../templates', __FILE__) +class Rails::InfoController < Rails::ApplicationController # :nodoc: prepend_view_path ActionDispatch::DebugExceptions::RESCUES_TEMPLATE_PATH - layout -> { request.xhr? ? nil : 'application' } + layout -> { request.xhr? ? false : 'application' } before_filter :require_local! @@ -20,16 +20,4 @@ class Rails::InfoController < ActionController::Base # :nodoc: @routes_inspector = ActionDispatch::Routing::RoutesInspector.new(_routes.routes) @page_title = 'Routes' end - - protected - - def require_local! - unless local_request? - render text: '<p>For security purposes, this information is only available to local requests.</p>', status: :forbidden - end - end - - def local_request? - Rails.application.config.consider_all_requests_local || request.local? - end end diff --git a/railties/lib/rails/mailers_controller.rb b/railties/lib/rails/mailers_controller.rb new file mode 100644 index 0000000000..dd318f52e5 --- /dev/null +++ b/railties/lib/rails/mailers_controller.rb @@ -0,0 +1,73 @@ +require 'rails/application_controller' + +class Rails::MailersController < Rails::ApplicationController # :nodoc: + prepend_view_path ActionDispatch::DebugExceptions::RESCUES_TEMPLATE_PATH + + before_filter :require_local! + before_filter :find_preview, only: :preview + + def index + @previews = ActionMailer::Preview.all + @page_title = "Mailer Previews" + end + + def preview + if params[:path] == @preview.preview_name + @page_title = "Mailer Previews for #{@preview.preview_name}" + render action: 'mailer' + else + email = File.basename(params[:path]) + + if @preview.email_exists?(email) + @email = @preview.call(email) + + if params[:part] + part_type = Mime::Type.lookup(params[:part]) + + if part = find_part(part_type) + response.content_type = part_type + render text: part.respond_to?(:decoded) ? part.decoded : part + else + raise AbstractController::ActionNotFound, "Email part '#{part_type}' not found in #{@preview.name}##{email}" + end + else + @part = find_preferred_part(request.format, Mime::HTML, Mime::TEXT) + render action: 'email', layout: false, formats: %w[html] + end + else + raise AbstractController::ActionNotFound, "Email '#{email}' not found in #{@preview.name}" + end + end + end + + protected + def find_preview + candidates = [] + params[:path].to_s.scan(%r{/|$}){ candidates << $` } + preview = candidates.detect{ |candidate| ActionMailer::Preview.exists?(candidate) } + + if preview + @preview = ActionMailer::Preview.find(preview) + else + raise AbstractController::ActionNotFound, "Mailer preview '#{params[:path]}' not found" + end + end + + def find_preferred_part(*formats) + if @email.multipart? + formats.each do |format| + return find_part(format) if @email.parts.any?{ |p| p.mime_type == format } + end + else + @email + end + end + + def find_part(format) + if @email.multipart? + @email.parts.find{ |p| p.mime_type == format } + elsif @email.mime_type == format + @email + end + end +end
\ No newline at end of file diff --git a/railties/lib/rails/templates/layouts/application.html.erb b/railties/lib/rails/templates/layouts/application.html.erb index 50a4755e45..5aecaa712a 100644 --- a/railties/lib/rails/templates/layouts/application.html.erb +++ b/railties/lib/rails/templates/layouts/application.html.erb @@ -29,7 +29,7 @@ </style> </head> <body> -<h2>Your App: <%= link_to 'properties', '/rails/info/properties' %> | <%= link_to 'routes', '/rails/info/routes' %></h2> + <%= yield %> </body> diff --git a/railties/lib/rails/templates/rails/mailers/email.html.erb b/railties/lib/rails/templates/rails/mailers/email.html.erb new file mode 100644 index 0000000000..977feb922b --- /dev/null +++ b/railties/lib/rails/templates/rails/mailers/email.html.erb @@ -0,0 +1,98 @@ +<!DOCTYPE html> +<html><head> +<meta name="viewport" content="width=device-width" /> +<style type="text/css"> + header { + width: 100%; + padding: 10px 0 0 0; + margin: 0; + background: white; + font: 12px "Lucida Grande", sans-serif; + border-bottom: 1px solid #dedede; + overflow: hidden; + } + + dl { + margin: 0 0 10px 0; + padding: 0; + } + + dt { + width: 80px; + padding: 1px; + float: left; + clear: left; + text-align: right; + color: #7f7f7f; + } + + dd { + margin-left: 90px; /* 80px + 10px */ + padding: 1px; + } + + iframe { + border: 0; + width: 100%; + height: 800px; + } +</style> +</head> + +<body> +<header> + <dl> + <% if @email.respond_to?(:smtp_envelope_from) && Array(@email.from) != Array(@email.smtp_envelope_from) %> + <dt>SMTP-From:</dt> + <dd><%= @email.smtp_envelope_from %></dd> + <% end %> + + <% if @email.respond_to?(:smtp_envelope_to) && @email.to != @email.smtp_envelope_to %> + <dt>SMTP-To:</dt> + <dd><%= @email.smtp_envelope_to %></dd> + <% end %> + + <dt>From:</dt> + <dd><%= @email.header['from'] %></dd> + + <% if @email.reply_to %> + <dt>Reply-To:</dt> + <dd><%= @email.header['reply-to'] %></dd> + <% end %> + + <dt>To:</dt> + <dd><%= @email.header['to'] %></dd> + + <% if @email.cc %> + <dt>CC:</dt> + <dd><%= @email.header['cc'] %></dd> + <% end %> + + <dt>Date:</dt> + <dd><%= Time.current.rfc2822 %></dd> + + <dt>Subject:</dt> + <dd><strong><%= @email.subject %></strong></dd> + + <% unless @email.attachments.nil? || @email.attachments.empty? %> + <dt>Attachments:</dt> + <dd> + <%= @email.attachments.map { |a| a.respond_to?(:original_filename) ? a.original_filename : a.filename }.inspect %> + </dd> + <% end %> + + <% if @email.multipart? %> + <dd> + <select onchange="document.getElementsByName('messageBody')[0].src=this.options[this.selectedIndex].value;"> + <option <%= request.format == Mime::HTML ? 'selected' : '' %> value="?part=text%2Fhtml">View as HTML email</option> + <option <%= request.format == Mime::TEXT ? 'selected' : '' %> value="?part=text%2Fplain">View as plain-text email</option> + </select> + </dd> + <% end %> + </dl> +</header> + +<iframe seamless name="messageBody" src="?part=<%= Rack::Utils.escape(@part.mime_type) %>"></iframe> + +</body> +</html>
\ No newline at end of file diff --git a/railties/lib/rails/templates/rails/mailers/index.html.erb b/railties/lib/rails/templates/rails/mailers/index.html.erb new file mode 100644 index 0000000000..c4c9757d57 --- /dev/null +++ b/railties/lib/rails/templates/rails/mailers/index.html.erb @@ -0,0 +1,8 @@ +<% @previews.each do |preview| %> +<h3><%= link_to preview.preview_name.titleize, "/rails/mailers/#{preview.preview_name}" %></h3> +<ul> +<% preview.emails.each do |email| %> +<li><%= link_to email, "/rails/mailers/#{preview.preview_name}/#{email}" %></li> +<% end %> +</ul> +<% end %> diff --git a/railties/lib/rails/templates/rails/mailers/mailer.html.erb b/railties/lib/rails/templates/rails/mailers/mailer.html.erb new file mode 100644 index 0000000000..607c8d1677 --- /dev/null +++ b/railties/lib/rails/templates/rails/mailers/mailer.html.erb @@ -0,0 +1,6 @@ +<h3><%= @preview.preview_name.titleize %></h3> +<ul> +<% @preview.emails.each do |email| %> +<li><%= link_to email, "/rails/mailers/#{@preview.preview_name}/#{email}" %></li> +<% end %> +</ul> diff --git a/railties/lib/rails/test_help.rb b/railties/lib/rails/test_help.rb index be801befc2..7765c9ae86 100644 --- a/railties/lib/rails/test_help.rb +++ b/railties/lib/rails/test_help.rb @@ -11,7 +11,7 @@ require 'rails/generators/test_case' # Config Rails backtrace in tests. require 'rails/backtrace_cleaner' if ENV["BACKTRACE"].nil? - MiniTest.backtrace_filter = Rails.backtrace_cleaner + Minitest.backtrace_filter = Rails.backtrace_cleaner end if defined?(ActiveRecord::Base) diff --git a/railties/lib/rails/version.rb b/railties/lib/rails/version.rb index 5a6d8d0983..923cab4e2a 100644 --- a/railties/lib/rails/version.rb +++ b/railties/lib/rails/version.rb @@ -3,7 +3,7 @@ module Rails MAJOR = 4 MINOR = 1 TINY = 0 - PRE = "beta" + PRE = "beta1" STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".") end diff --git a/railties/lib/rails/welcome_controller.rb b/railties/lib/rails/welcome_controller.rb index 45b764fa6b..de9cd18b01 100644 --- a/railties/lib/rails/welcome_controller.rb +++ b/railties/lib/rails/welcome_controller.rb @@ -1,6 +1,7 @@ -class Rails::WelcomeController < ActionController::Base # :nodoc: - self.view_paths = File.expand_path('../templates', __FILE__) - layout nil +require 'rails/application_controller' + +class Rails::WelcomeController < Rails::ApplicationController # :nodoc: + layout false def index end diff --git a/railties/test/application/configuration_test.rb b/railties/test/application/configuration_test.rb index e024ec8cef..7a8fed6732 100644 --- a/railties/test/application/configuration_test.rb +++ b/railties/test/application/configuration_test.rb @@ -274,11 +274,11 @@ module ApplicationTests app.config.session_store :disabled end - message = app.message_verifier('salt').generate("some_value") + message = app.message_verifier(:sensitive_value).generate("some_value") - assert_equal 'some_value', Rails.application.message_verifier('salt').verify(message) + assert_equal 'some_value', Rails.application.message_verifier(:sensitive_value).verify(message) - secret = app.key_generator.generate_key('salt') + secret = app.key_generator.generate_key('sensitive_value') verifier = ActiveSupport::MessageVerifier.new(secret) assert_equal 'some_value', verifier.verify(message) end @@ -289,8 +289,8 @@ module ApplicationTests app.config.session_store :disabled end - default_verifier = app.message_verifier('salt') - text_verifier = app.message_verifier('text') + default_verifier = app.message_verifier(:sensitive_value) + text_verifier = app.message_verifier(:text) message = text_verifier.generate('some_value') @@ -299,7 +299,7 @@ module ApplicationTests default_verifier.verify(message) end - assert_equal default_verifier.object_id, app.message_verifier('salt').object_id + assert_equal default_verifier.object_id, app.message_verifier(:sensitive_value).object_id assert_not_equal default_verifier.object_id, text_verifier.object_id end diff --git a/railties/test/application/initializers/i18n_test.rb b/railties/test/application/initializers/i18n_test.rb index 2a64cd8ba7..bc34897cdf 100644 --- a/railties/test/application/initializers/i18n_test.rb +++ b/railties/test/application/initializers/i18n_test.rb @@ -184,14 +184,48 @@ en: assert_fallbacks ca: [:ca, :"es-ES", :es, :'en-US', :en] end - test "config.i18n.enforce_available_locales is set before config.i18n.default_locale is" do + test "config.i18n.enforce_available_locales is set to true by default and avoids I18n warnings" do add_to_config <<-RUBY config.i18n.default_locale = :it - config.i18n.enforce_available_locales = true RUBY - assert_raises(I18n::InvalidLocale) do - load_app + output = capture(:stderr) { load_app } + assert_no_match %r{deprecated.*enforce_available_locales}, output + assert_equal true, I18n.enforce_available_locales + + assert_raise I18n::InvalidLocale do + I18n.locale = :es + end + end + + test "disable config.i18n.enforce_available_locales" do + add_to_config <<-RUBY + config.i18n.enforce_available_locales = false + config.i18n.default_locale = :fr + RUBY + + output = capture(:stderr) { load_app } + assert_no_match %r{deprecated.*enforce_available_locales}, output + assert_equal false, I18n.enforce_available_locales + + assert_nothing_raised do + I18n.locale = :es + end + end + + test "default config.i18n.enforce_available_locales does not override I18n.enforce_available_locales" do + I18n.enforce_available_locales = false + + add_to_config <<-RUBY + config.i18n.default_locale = :fr + RUBY + + output = capture(:stderr) { load_app } + assert_no_match %r{deprecated.*enforce_available_locales}, output + assert_equal false, I18n.enforce_available_locales + + assert_nothing_raised do + I18n.locale = :es end end end diff --git a/railties/test/application/mailer_previews_test.rb b/railties/test/application/mailer_previews_test.rb new file mode 100644 index 0000000000..14abb33cc6 --- /dev/null +++ b/railties/test/application/mailer_previews_test.rb @@ -0,0 +1,388 @@ +require 'isolation/abstract_unit' +require 'rack/test' +module ApplicationTests + class MailerPreviewsTest < ActiveSupport::TestCase + include ActiveSupport::Testing::Isolation + include Rack::Test::Methods + + def setup + build_app + boot_rails + end + + def teardown + teardown_app + end + + test "/rails/mailers is accessible in development" do + app("development") + get "/rails/mailers" + assert_equal 200, last_response.status + end + + test "/rails/mailers is not accessible in production" do + app("production") + get "/rails/mailers" + assert_equal 404, last_response.status + end + + test "mailer previews are loaded from the default preview_path" do + mailer 'notifier', <<-RUBY + class Notifier < ActionMailer::Base + default from: "from@example.com" + + def foo + mail to: "to@example.org" + end + end + RUBY + + text_template 'notifier/foo', <<-RUBY + Hello, World! + RUBY + + mailer_preview 'notifier', <<-RUBY + class NotifierPreview < ActionMailer::Preview + def foo + Notifier.foo + end + end + RUBY + + app('development') + + get "/rails/mailers" + assert_match '<h3><a href="/rails/mailers/notifier">Notifier</a></h3>', last_response.body + assert_match '<li><a href="/rails/mailers/notifier/foo">foo</a></li>', last_response.body + end + + test "mailer previews are loaded from a custom preview_path" do + add_to_config "config.action_mailer.preview_path = '#{app_path}/lib/mailer_previews'" + + mailer 'notifier', <<-RUBY + class Notifier < ActionMailer::Base + default from: "from@example.com" + + def foo + mail to: "to@example.org" + end + end + RUBY + + text_template 'notifier/foo', <<-RUBY + Hello, World! + RUBY + + app_file 'lib/mailer_previews/notifier_preview.rb', <<-RUBY + class NotifierPreview < ActionMailer::Preview + def foo + Notifier.foo + end + end + RUBY + + app('development') + + get "/rails/mailers" + assert_match '<h3><a href="/rails/mailers/notifier">Notifier</a></h3>', last_response.body + assert_match '<li><a href="/rails/mailers/notifier/foo">foo</a></li>', last_response.body + end + + test "mailer previews are reloaded across requests" do + app('development') + + get "/rails/mailers" + assert_no_match '<h3><a href="/rails/mailers/notifier">Notifier</a></h3>', last_response.body + + mailer 'notifier', <<-RUBY + class Notifier < ActionMailer::Base + default from: "from@example.com" + + def foo + mail to: "to@example.org" + end + end + RUBY + + text_template 'notifier/foo', <<-RUBY + Hello, World! + RUBY + + mailer_preview 'notifier', <<-RUBY + class NotifierPreview < ActionMailer::Preview + def foo + Notifier.foo + end + end + RUBY + + get "/rails/mailers" + assert_match '<h3><a href="/rails/mailers/notifier">Notifier</a></h3>', last_response.body + + remove_file 'test/mailers/previews/notifier_preview.rb' + sleep(1) + + get "/rails/mailers" + assert_no_match '<h3><a href="/rails/mailers/notifier">Notifier</a></h3>', last_response.body + end + + test "mailer preview actions are added and removed" do + mailer 'notifier', <<-RUBY + class Notifier < ActionMailer::Base + default from: "from@example.com" + + def foo + mail to: "to@example.org" + end + end + RUBY + + text_template 'notifier/foo', <<-RUBY + Hello, World! + RUBY + + mailer_preview 'notifier', <<-RUBY + class NotifierPreview < ActionMailer::Preview + def foo + Notifier.foo + end + end + RUBY + + app('development') + + get "/rails/mailers" + assert_match '<h3><a href="/rails/mailers/notifier">Notifier</a></h3>', last_response.body + assert_match '<li><a href="/rails/mailers/notifier/foo">foo</a></li>', last_response.body + assert_no_match '<li><a href="/rails/mailers/notifier/bar">bar</a></li>', last_response.body + + mailer 'notifier', <<-RUBY + class Notifier < ActionMailer::Base + default from: "from@example.com" + + def foo + mail to: "to@example.org" + end + + def bar + mail to: "to@example.net" + end + end + RUBY + + text_template 'notifier/foo', <<-RUBY + Hello, World! + RUBY + + text_template 'notifier/bar', <<-RUBY + Goodbye, World! + RUBY + + mailer_preview 'notifier', <<-RUBY + class NotifierPreview < ActionMailer::Preview + def foo + Notifier.foo + end + + def bar + Notifier.bar + end + end + RUBY + + sleep(1) + + get "/rails/mailers" + assert_match '<h3><a href="/rails/mailers/notifier">Notifier</a></h3>', last_response.body + assert_match '<li><a href="/rails/mailers/notifier/foo">foo</a></li>', last_response.body + assert_match '<li><a href="/rails/mailers/notifier/bar">bar</a></li>', last_response.body + + mailer 'notifier', <<-RUBY + class Notifier < ActionMailer::Base + default from: "from@example.com" + + def foo + mail to: "to@example.org" + end + end + RUBY + + remove_file 'app/views/notifier/bar.text.erb' + + mailer_preview 'notifier', <<-RUBY + class NotifierPreview < ActionMailer::Preview + def foo + Notifier.foo + end + end + RUBY + + sleep(1) + + get "/rails/mailers" + assert_match '<h3><a href="/rails/mailers/notifier">Notifier</a></h3>', last_response.body + assert_match '<li><a href="/rails/mailers/notifier/foo">foo</a></li>', last_response.body + assert_no_match '<li><a href="/rails/mailers/notifier/bar">bar</a></li>', last_response.body + end + + test "mailer preview not found" do + app('development') + get "/rails/mailers/notifier" + assert last_response.not_found? + assert_match "Mailer preview 'notifier' not found", last_response.body + end + + test "mailer preview email not found" do + mailer 'notifier', <<-RUBY + class Notifier < ActionMailer::Base + default from: "from@example.com" + + def foo + mail to: "to@example.org" + end + end + RUBY + + text_template 'notifier/foo', <<-RUBY + Hello, World! + RUBY + + mailer_preview 'notifier', <<-RUBY + class NotifierPreview < ActionMailer::Preview + def foo + Notifier.foo + end + end + RUBY + + app('development') + + get "/rails/mailers/notifier/bar" + assert last_response.not_found? + assert_match "Email 'bar' not found in NotifierPreview", last_response.body + end + + test "mailer preview email part not found" do + mailer 'notifier', <<-RUBY + class Notifier < ActionMailer::Base + default from: "from@example.com" + + def foo + mail to: "to@example.org" + end + end + RUBY + + text_template 'notifier/foo', <<-RUBY + Hello, World! + RUBY + + mailer_preview 'notifier', <<-RUBY + class NotifierPreview < ActionMailer::Preview + def foo + Notifier.foo + end + end + RUBY + + app('development') + + get "/rails/mailers/notifier/foo?part=text%2Fhtml" + assert last_response.not_found? + assert_match "Email part 'text/html' not found in NotifierPreview#foo", last_response.body + end + + test "message header uses full display names" do + mailer 'notifier', <<-RUBY + class Notifier < ActionMailer::Base + default from: "Ruby on Rails <core@rubyonrails.org>" + + def foo + mail to: "Andrew White <andyw@pixeltrix.co.uk>", + cc: "David Heinemeier Hansson <david@heinemeierhansson.com>" + end + end + RUBY + + text_template 'notifier/foo', <<-RUBY + Hello, World! + RUBY + + mailer_preview 'notifier', <<-RUBY + class NotifierPreview < ActionMailer::Preview + def foo + Notifier.foo + end + end + RUBY + + app('development') + + get "/rails/mailers/notifier/foo" + assert_equal 200, last_response.status + assert_match "Ruby on Rails <core@rubyonrails.org>", last_response.body + assert_match "Andrew White <andyw@pixeltrix.co.uk>", last_response.body + assert_match "David Heinemeier Hansson <david@heinemeierhansson.com>", last_response.body + end + + test "part menu selects correct option" do + mailer 'notifier', <<-RUBY + class Notifier < ActionMailer::Base + default from: "from@example.com" + + def foo + mail to: "to@example.org" + end + end + RUBY + + html_template 'notifier/foo', <<-RUBY + <p>Hello, World!</p> + RUBY + + text_template 'notifier/foo', <<-RUBY + Hello, World! + RUBY + + mailer_preview 'notifier', <<-RUBY + class NotifierPreview < ActionMailer::Preview + def foo + Notifier.foo + end + end + RUBY + + app('development') + + get "/rails/mailers/notifier/foo.html" + assert_equal 200, last_response.status + assert_match '<option selected value="?part=text%2Fhtml">View as HTML email</option>', last_response.body + + get "/rails/mailers/notifier/foo.txt" + assert_equal 200, last_response.status + assert_match '<option selected value="?part=text%2Fplain">View as plain-text email</option>', last_response.body + end + + private + def build_app + super + app_file 'config/routes.rb', "Rails.application.routes.draw do; end" + end + + def mailer(name, contents) + app_file("app/mailers/#{name}.rb", contents) + end + + def mailer_preview(name, contents) + app_file("test/mailers/previews/#{name}_preview.rb", contents) + end + + def html_template(name, contents) + app_file("app/views/#{name}.html.erb", contents) + end + + def text_template(name, contents) + app_file("app/views/#{name}.text.erb", contents) + end + end +end diff --git a/railties/test/application/rake_test.rb b/railties/test/application/rake_test.rb index 08316d80e6..33d3c4a19e 100644 --- a/railties/test/application/rake_test.rb +++ b/railties/test/application/rake_test.rb @@ -208,7 +208,8 @@ module ApplicationTests add_to_config "config.active_record.schema_format = :sql" output = Dir.chdir(app_path) do `rails generate scaffold user username:string; - bundle exec rake db:migrate db:test:clone 2>&1 --trace` + bundle exec rake db:migrate; + bundle exec rake db:test:clone 2>&1 --trace` end assert_match(/Execute db:test:clone_structure/, output) end @@ -217,7 +218,8 @@ module ApplicationTests add_to_config "config.active_record.schema_format = :sql" output = Dir.chdir(app_path) do `rails generate scaffold user username:string; - bundle exec rake db:migrate db:test:prepare 2>&1 --trace` + bundle exec rake db:migrate; + bundle exec rake db:test:prepare 2>&1 --trace` end assert_match(/Execute db:test:load_structure/, output) end diff --git a/railties/test/commands/dbconsole_test.rb b/railties/test/commands/dbconsole_test.rb index edb92b3aa2..a6cd6ec61d 100644 --- a/railties/test/commands/dbconsole_test.rb +++ b/railties/test/commands/dbconsole_test.rb @@ -2,29 +2,72 @@ require 'abstract_unit' require 'rails/commands/dbconsole' class Rails::DBConsoleTest < ActiveSupport::TestCase - def teardown - %w[PGUSER PGHOST PGPORT PGPASSWORD].each{|key| ENV.delete(key)} - end - def test_config - Rails::DBConsole.const_set(:APP_PATH, "erb") - - app_config({}) - capture_abort { Rails::DBConsole.new.config } - assert aborted - assert_match(/No database is configured for the environment '\w+'/, output) - app_config(test: "with_init") - assert_equal Rails::DBConsole.new.config, "with_init" - - app_db_file("test:\n without_init") - assert_equal Rails::DBConsole.new.config, "without_init" - - app_db_file("test:\n <%= Rails.something_app_specific %>") - assert_equal Rails::DBConsole.new.config, "with_init" + def setup + Rails::DBConsole.const_set('APP_PATH', 'rails/all') + end - app_db_file("test:\n\ninvalid") - assert_equal Rails::DBConsole.new.config, "with_init" + def teardown + Rails::DBConsole.send(:remove_const, 'APP_PATH') + %w[PGUSER PGHOST PGPORT PGPASSWORD DATABASE_URL].each{|key| ENV.delete(key)} + end + + def test_config_with_db_config_only + config_sample = { + "test"=> { + "adapter"=> "sqlite3", + "host"=> "localhost", + "port"=> "9000", + "database"=> "foo_test", + "user"=> "foo", + "password"=> "bar", + "pool"=> "5", + "timeout"=> "3000" + } + } + app_db_config(config_sample) + assert_equal Rails::DBConsole.new.config, config_sample["test"] + end + + def test_config_with_no_db_config + app_db_config(nil) + assert_raise(ActiveRecord::AdapterNotSpecified) { + Rails::DBConsole.new.config + } + end + + def test_config_with_database_url_only + ENV['DATABASE_URL'] = 'sqlite3://foo:bar@localhost:9000/foo_test?pool=5&timeout=3000' + app_db_config(nil) + assert_equal Rails::DBConsole.new.config.sort, { + "adapter"=> "sqlite3", + "host"=> "localhost", + "port"=> 9000, + "database"=> "foo_test", + "username"=> "foo", + "password"=> "bar", + "pool"=> "5", + "timeout"=> "3000" + }.sort + end + + def test_config_choose_database_url_if_exists + ENV['DATABASE_URL'] = 'sqlite3://foo:bar@dburl:9000/foo_test?pool=5&timeout=3000' + sample_config = { + "test" => { + "adapter"=> "sqlite3", + "host"=> "localhost", + "port"=> 9000, + "database"=> "foo_test", + "username"=> "foo", + "password"=> "bar", + "pool"=> "5", + "timeout"=> "3000" + } + } + app_db_config(sample_config) + assert_equal Rails::DBConsole.new.config["host"], "dburl" end def test_env @@ -177,6 +220,10 @@ class Rails::DBConsoleTest < ActiveSupport::TestCase private + def app_db_config(results) + Rails.application.config.stubs(:database_configuration).returns(results) + end + def dbconsole @dbconsole ||= Rails::DBConsole.new(nil) end @@ -197,11 +244,4 @@ class Rails::DBConsoleTest < ActiveSupport::TestCase end end - def app_db_file(result) - IO.stubs(:read).with("config/database.yml").returns(result) - end - - def app_config(result) - Rails.application.config.stubs(:database_configuration).returns(result.stringify_keys) - end end diff --git a/railties/test/configuration/middleware_stack_proxy_test.rb b/railties/test/configuration/middleware_stack_proxy_test.rb index 2442cb995d..6f3e45f320 100644 --- a/railties/test/configuration/middleware_stack_proxy_test.rb +++ b/railties/test/configuration/middleware_stack_proxy_test.rb @@ -39,7 +39,7 @@ module Rails @stack.swap :foo @stack.delete :foo - mock = MiniTest::Mock.new + mock = Minitest::Mock.new mock.expect :send, nil, [:swap, :foo] mock.expect :send, nil, [:delete, :foo] @@ -50,7 +50,7 @@ module Rails private def assert_playback(msg_name, args) - mock = MiniTest::Mock.new + mock = Minitest::Mock.new mock.expect :send, nil, [msg_name, args] @stack.merge_into(mock) mock.verify diff --git a/railties/test/generators/generators_test_helper.rb b/railties/test/generators/generators_test_helper.rb index 32a3d072c9..77ec2f1c0c 100644 --- a/railties/test/generators/generators_test_helper.rb +++ b/railties/test/generators/generators_test_helper.rb @@ -1,10 +1,14 @@ require 'abstract_unit' +require 'active_support/core_ext/module/remove_method' require 'rails/generators' require 'rails/generators/test_case' module Rails - def self.root - @root ||= File.expand_path(File.join(File.dirname(__FILE__), '..', 'fixtures')) + class << self + remove_possible_method :root + def root + @root ||= File.expand_path(File.join(File.dirname(__FILE__), '..', 'fixtures')) + end end end Rails.application.config.root = Rails.root diff --git a/railties/test/generators/mailer_generator_test.rb b/railties/test/generators/mailer_generator_test.rb index 6b2351fc1a..120ff3a2df 100644 --- a/railties/test/generators/mailer_generator_test.rb +++ b/railties/test/generators/mailer_generator_test.rb @@ -1,7 +1,6 @@ require 'generators/generators_test_helper' require 'rails/generators/mailer/mailer_generator' - class MailerGeneratorTest < Rails::Generators::TestCase include GeneratorsTestHelper arguments %w(notifier foo bar) @@ -23,8 +22,11 @@ class MailerGeneratorTest < Rails::Generators::TestCase end def test_check_class_collision - content = capture(:stderr){ run_generator ["object"] } - assert_match(/The name 'Object' is either already used in your application or reserved/, content) + Object.send :const_set, :Notifier, Class.new + content = capture(:stderr){ run_generator } + assert_match(/The name 'Notifier' is either already used in your application or reserved/, content) + ensure + Object.send :remove_const, :Notifier end def test_invokes_default_test_framework @@ -34,6 +36,31 @@ class MailerGeneratorTest < Rails::Generators::TestCase assert_match(/test "foo"/, test) assert_match(/test "bar"/, test) end + assert_file "test/mailers/previews/notifier_preview.rb" do |mailer| + assert_match(/class NotifierPreview < ActionMailer::Preview/, mailer) + assert_instance_method :foo, mailer do |foo| + assert_match(/Notifier.foo/, foo) + end + assert_instance_method :bar, mailer do |bar| + assert_match(/Notifier.bar/, bar) + end + end + end + + def test_check_test_class_collision + Object.send :const_set, :NotifierTest, Class.new + content = capture(:stderr){ run_generator } + assert_match(/The name 'NotifierTest' is either already used in your application or reserved/, content) + ensure + Object.send :remove_const, :NotifierTest + end + + def test_check_preview_class_collision + Object.send :const_set, :NotifierPreview, Class.new + content = capture(:stderr){ run_generator } + assert_match(/The name 'NotifierPreview' is either already used in your application or reserved/, content) + ensure + Object.send :remove_const, :NotifierPreview end def test_invokes_default_template_engine @@ -65,6 +92,9 @@ class MailerGeneratorTest < Rails::Generators::TestCase assert_match(/class Farm::Animal < ActionMailer::Base/, mailer) assert_match(/en\.farm\.animal\.moos\.subject/, mailer) end + assert_file "test/mailers/previews/farm/animal_preview.rb" do |mailer| + assert_match(/class Farm::AnimalPreview < ActionMailer::Preview/, mailer) + end assert_file "app/views/farm/animal/moos.text.erb" end |