diff options
Diffstat (limited to 'actionmailer')
59 files changed, 1023 insertions, 302 deletions
diff --git a/actionmailer/CHANGELOG.md b/actionmailer/CHANGELOG.md index ab93745f60..0ecb0235bc 100644 --- a/actionmailer/CHANGELOG.md +++ b/actionmailer/CHANGELOG.md @@ -1,30 +1,92 @@ -* Deprecate `*_path` helpers in email views. When used they generate - non-working links and are not the intention of most developers. Instead - we recommend to use `*_url` helper. +* `config.force_ssl = true` will set + `config.action_mailer.default_url_options = { protocol: 'https' }` - *Richard Schneeman* + *Andrew Kampjes* -* Raise an exception when attachments are added after `mail` was called. - This is a safeguard to prevent invalid emails. +* Add `config.action_mailer.deliver_later_queue_name` configuration to set the + mailer queue name. - Fixes #16163. + *Chris McGrath* - *Yves Senn* +* `assert_emails` in block form use the given number as expected value. + This makes the error message much easier to understand. + + *Yuji Yaginuma* -* Add `config.action_mailer.show_previews` configuration option. +* Add support for inline images in mailer previews by using an interceptor + class to convert cid: urls in image src attributes to data urls. - This config option can be used to enable the mail preview in environments - other than development (such as staging). + *Andrew White* - Defaults to `true` in development and false elsewhere. +* Mailer preview now uses `url_for` to fix links to emails for apps running on + a subdirectory. - *Leonard Garvey* + *Remo Mueller* -* Allow preview interceptors to be registered through - `config.action_mailer.preview_interceptors`. +* Mailer previews no longer crash when the `mail` method wasn't called + (`NullMail`). - See #15739. + Fixes #19849. *Yves Senn* -Please check [4-1-stable](https://github.com/rails/rails/blob/4-1-stable/actionmailer/CHANGELOG.md) for previous changes. +* Make sure labels and values line up in mailer previews. + + *Yves Senn* + +* Add `assert_enqueued_emails` and `assert_no_enqueued_emails`. + + Example: + + def test_emails + assert_enqueued_emails 2 do + ContactMailer.welcome.deliver_later + ContactMailer.welcome.deliver_later + end + end + + def test_no_emails + assert_no_enqueued_emails do + # No emails enqueued here + end + end + + *George Claghorn* + +* Add `_mailer` suffix to mailers created via generator, following the same + naming convention used in controllers and jobs. + + *Carlos Souza* + +* Remove deprecate `*_path` helpers in email views. + + *Rafael Mendonça França* + +* Remove deprecated `deliver` and `deliver!` methods. + + *claudiob* + +* Template lookup now respects default locale and I18n fallbacks. + + Given the following templates: + + mailer/demo.html.erb + mailer/demo.en.html.erb + mailer/demo.pt.html.erb + + Before this change, for a locale that doesn't have its associated file, the + `mailer/demo.html.erb` would be rendered even if `en` was the default locale. + + Now `mailer/demo.en.html.erb` has precedence over the file without locale. + + Also, it is possible to give a fallback. + + mailer/demo.pt.html.erb + mailer/demo.pt-BR.html.erb + + So if the locale is `pt-PT`, `mailer/demo.pt.html.erb` will be rendered given + the right I18n fallback configuration. + + *Rafael Mendonça França* + +Please check [4-2-stable](https://github.com/rails/rails/blob/4-2-stable/actionmailer/CHANGELOG.md) for previous changes. diff --git a/actionmailer/MIT-LICENSE b/actionmailer/MIT-LICENSE index d58dd9ed9b..3ec7a617cf 100644 --- a/actionmailer/MIT-LICENSE +++ b/actionmailer/MIT-LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2004-2014 David Heinemeier Hansson +Copyright (c) 2004-2015 David Heinemeier Hansson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the diff --git a/actionmailer/README.rdoc b/actionmailer/README.rdoc index ceca912ada..e5c2ed8c77 100644 --- a/actionmailer/README.rdoc +++ b/actionmailer/README.rdoc @@ -61,22 +61,30 @@ generated would look like this: Thank you for signing up! -In order to send mails, you simply call the method and then call +deliver+ on the return value. +In order to send mails, you simply call the method and then call +deliver_now+ on the return value. Calling the method returns a Mail Message object: - message = Notifier.welcome("david@loudthinking.com") # => Returns a Mail::Message object - message.deliver # => delivers the email + message = Notifier.welcome("david@loudthinking.com") # => Returns a Mail::Message object + message.deliver_now # => delivers the email Or you can just chain the methods together like: - Notifier.welcome("david@loudthinking.com").deliver # Creates the email and sends it immediately + Notifier.welcome("david@loudthinking.com").deliver_now # Creates the email and sends it immediately == Setting defaults -It is possible to set default values that will be used in every method in your Action Mailer class. To implement this functionality, you just call the public class method <tt>default</tt> which you get for free from <tt>ActionMailer::Base</tt>. This method accepts a Hash as the parameter. You can use any of the headers email messages have, like <tt>:from</tt> as the key. You can also pass in a string as the key, like "Content-Type", but Action Mailer does this out of the box for you, so you won't need to worry about that. Finally, it is also possible to pass in a Proc that will get evaluated when it is needed. +It is possible to set default values that will be used in every method in your +Action Mailer class. To implement this functionality, you just call the public +class method +default+ which you get for free from <tt>ActionMailer::Base</tt>. +This method accepts a Hash as the parameter. You can use any of the headers, +email messages have, like +:from+ as the key. You can also pass in a string as +the key, like "Content-Type", but Action Mailer does this out of the box for you, +so you won't need to worry about that. Finally, it is also possible to pass in a +Proc that will get evaluated when it is needed. -Note that every value you set with this method will get overwritten if you use the same key in your mailer method. +Note that every value you set with this method will get overwritten if you use the +same key in your mailer method. Example: @@ -87,10 +95,11 @@ Example: == Receiving emails -To receive emails, you need to implement a public instance method called <tt>receive</tt> that takes an -email object as its single parameter. The Action Mailer framework has a corresponding class method, -which is also called <tt>receive</tt>, that accepts a raw, unprocessed email as a string, which it then turns -into the email object and calls the receive instance method. +To receive emails, you need to implement a public instance method called ++receive+ that takes an email object as its single parameter. The Action Mailer +framework has a corresponding class method, which is also called +receive+, that +accepts a raw, unprocessed email as a string, which it then turns into the email +object and calls the receive instance method. Example: @@ -111,13 +120,14 @@ Example: end end -This Mailman can be the target for Postfix or other MTAs. In Rails, you would use the runner in the -trivial case like this: +This Mailman can be the target for Postfix or other MTAs. In Rails, you would use +the runner in the trivial case like this: rails runner 'Mailman.receive(STDIN.read)' -However, invoking Rails in the runner for each mail to be received is very resource intensive. A single -instance of Rails should be run within a daemon, if it is going to process more than just a limited amount of email. +However, invoking Rails in the runner for each mail to be received is very +resource intensive. A single instance of Rails should be run within a daemon, if +it is going to process more than just a limited amount of email. == Configuration @@ -136,7 +146,7 @@ The Base class has the full list of configuration options. Here's an example: The latest version of Action Mailer can be installed with RubyGems: - % [sudo] gem install actionmailer + % gem install actionmailer Source code can be downloaded as part of the Rails project on GitHub diff --git a/actionmailer/Rakefile b/actionmailer/Rakefile index 5ddd90020b..7197ea5e27 100644 --- a/actionmailer/Rakefile +++ b/actionmailer/Rakefile @@ -1,5 +1,4 @@ require 'rake/testtask' -require 'rubygems/package_task' desc "Default Task" task default: [ :test ] @@ -10,6 +9,7 @@ Rake::TestTask.new { |t| t.pattern = 'test/**/*_test.rb' t.warning = true t.verbose = true + t.ruby_opts = ["--dev"] if defined?(JRUBY_VERSION) } namespace :test do @@ -19,16 +19,3 @@ namespace :test do end or raise "Failures" end end - -spec = eval(File.read('actionmailer.gemspec')) - -Gem::PackageTask.new(spec) do |p| - p.gem_spec = spec -end - -desc "Release to rubygems" -task release: :package do - require 'rake/gemcutter' - Rake::Gemcutter::Tasks.new(spec).define - Rake::Task['gem:push'].invoke -end diff --git a/actionmailer/actionmailer.gemspec b/actionmailer/actionmailer.gemspec index 01d97b7213..782b208ef4 100644 --- a/actionmailer/actionmailer.gemspec +++ b/actionmailer/actionmailer.gemspec @@ -7,7 +7,7 @@ Gem::Specification.new do |s| s.summary = 'Email composition, delivery, and receiving framework (part of Rails).' s.description = 'Email on Rails. Compose, deliver, receive, and test emails using the familiar controller/view pattern. First-class support for multipart email and attachments.' - s.required_ruby_version = '>= 1.9.3' + s.required_ruby_version = '>= 2.2.2' s.license = 'MIT' @@ -21,6 +21,8 @@ Gem::Specification.new do |s| s.add_dependency 'actionpack', version s.add_dependency 'actionview', version + s.add_dependency 'activejob', version s.add_dependency 'mail', ['~> 2.5', '>= 2.5.4'] + s.add_dependency 'rails-dom-testing', '~> 1.0', '>= 1.0.5' end diff --git a/actionmailer/bin/test b/actionmailer/bin/test new file mode 100755 index 0000000000..404cabba51 --- /dev/null +++ b/actionmailer/bin/test @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby +COMPONENT_ROOT = File.expand_path("../../", __FILE__) +require File.expand_path("../tools/test", COMPONENT_ROOT) +exit Minitest.run(ARGV) diff --git a/actionmailer/lib/action_mailer.rb b/actionmailer/lib/action_mailer.rb index 83969d4074..312dd1997c 100644 --- a/actionmailer/lib/action_mailer.rb +++ b/actionmailer/lib/action_mailer.rb @@ -1,5 +1,5 @@ #-- -# Copyright (c) 2004-2014 David Heinemeier Hansson +# Copyright (c) 2004-2015 David Heinemeier Hansson # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -40,9 +40,19 @@ module ActionMailer autoload :Base autoload :DeliveryMethods + autoload :InlinePreviewInterceptor autoload :MailHelper autoload :Preview autoload :Previews, 'action_mailer/preview' autoload :TestCase autoload :TestHelper + autoload :MessageDelivery + autoload :DeliveryJob +end + +autoload :Mime, 'action_dispatch/http/mime_type' + +ActiveSupport.on_load(:action_view) do + ActionView::Base.default_formats ||= Mime::SET.symbols + ActionView::Template::Types.delegate_to Mime end diff --git a/actionmailer/lib/action_mailer/base.rb b/actionmailer/lib/action_mailer/base.rb index bc540aece0..c9e7f7d0d3 100644 --- a/actionmailer/lib/action_mailer/base.rb +++ b/actionmailer/lib/action_mailer/base.rb @@ -15,11 +15,17 @@ module ActionMailer # # $ rails generate mailer Notifier # - # The generated model inherits from <tt>ActionMailer::Base</tt>. A mailer model defines methods + # The generated model inherits from <tt>ApplicationMailer</tt> which in turn + # inherits from <tt>ActionMailer::Base</tt>. A mailer model defines methods # used to generate an email message. In these methods, you can setup variables to be used in # the mailer views, options on the mail itself such as the <tt>:from</tt> address, and attachments. # - # class Notifier < ActionMailer::Base + # class ApplicationMailer < ActionMailer::Base + # default from: 'from@example.com' + # layout 'mailer' + # end + # + # class NotifierMailer < ApplicationMailer # default from: 'no-reply@example.com', # return_path: 'system@example.com' # @@ -39,11 +45,8 @@ module ActionMailer # in the same manner as <tt>attachments[]=</tt> # # * <tt>headers[]=</tt> - Allows you to specify any header field in your email such - # as <tt>headers['X-No-Spam'] = 'True'</tt>. Note, while most fields like <tt>To:</tt> - # <tt>From:</tt> can only appear once in an email header, other fields like <tt>X-Anything</tt> - # can appear multiple times. If you want to change a field that can appear multiple times, - # you need to set it to nil first so that Mail knows you are replacing it and not adding - # another field of the same name. + # as <tt>headers['X-No-Spam'] = 'True'</tt>. Note that declaring a header multiple times + # will add many fields of the same name. Read #headers doc for more information. # # * <tt>headers(hash)</tt> - Allows you to specify multiple headers in your email such # as <tt>headers({'X-No-Spam' => 'True', 'In-Reply-To' => '1234@message.id'})</tt> @@ -55,7 +58,7 @@ module ActionMailer # # The mail method, if not passed a block, will inspect your views and send all the views with # the same name as the method, so the above action would send the +welcome.text.erb+ view - # file as well as the +welcome.text.html.erb+ view file in a +multipart/alternative+ email. + # file as well as the +welcome.html.erb+ view file in a +multipart/alternative+ email. # # If you want to explicitly render only certain templates, pass a block: # @@ -85,9 +88,10 @@ module ActionMailer # # To define a template to be used with a mailing, create an <tt>.erb</tt> file with the same # name as the method in your mailer model. For example, in the mailer defined above, the template at - # <tt>app/views/notifier/welcome.text.erb</tt> would be used to generate the email. + # <tt>app/views/notifier_mailer/welcome.text.erb</tt> would be used to generate the email. # - # Variables defined in the model are accessible as instance variables in the view. + # Variables defined in the methods of your mailer model are accessible as instance variables in their + # corresponding view. # # Emails by default are sent in plain text, so a sample view for our model example might look like this: # @@ -128,21 +132,32 @@ module ActionMailer # # config.action_mailer.default_url_options = { host: "example.com" } # - # When you decide to set a default <tt>:host</tt> for your mailers, then you need to make sure to use the - # <tt>only_path: false</tt> option when using <tt>url_for</tt>. Since the <tt>url_for</tt> view helper - # will generate relative URLs by default when a <tt>:host</tt> option isn't explicitly provided, passing - # <tt>only_path: false</tt> will ensure that absolute URLs are generated. + # By default when <tt>config.force_ssl</tt> is true, URLs generated for hosts will use the HTTPS protocol. # # = Sending mail # - # Once a mailer action and template are defined, you can deliver your message or create it and save it - # for delivery later: + # Once a mailer action and template are defined, you can deliver your message or defer its creation and + # delivery for later: + # + # NotifierMailer.welcome(User.first).deliver_now # sends the email + # mail = NotifierMailer.welcome(User.first) # => an ActionMailer::MessageDelivery object + # mail.deliver_now # generates and sends the email now + # + # The <tt>ActionMailer::MessageDelivery</tt> class is a wrapper around a delegate that will call + # your method to generate the mail. If you want direct access to delegator, or <tt>Mail::Message</tt>, + # you can call the <tt>message</tt> method on the <tt>ActionMailer::MessageDelivery</tt> object. # - # Notifier.welcome(david).deliver # sends the email - # mail = Notifier.welcome(david) # => a Mail::Message object - # mail.deliver # sends the email + # NotifierMailer.welcome(User.first).message # => a Mail::Message object + # + # Action Mailer is nicely integrated with Active Job so you can generate and send emails in the background + # (example: outside of the request-response cycle, so the user doesn't have to wait on it): + # + # NotifierMailer.welcome(User.first).deliver_later # enqueue the email sending to Active Job + # + # Note that <tt>deliver_later</tt> will execute your method from the background job. # # You never instantiate your mailer class. Rather, you just call the method you defined on the class itself. + # All instance methods are expected to return a message object to be sent. # # = Multipart Emails # @@ -169,7 +184,7 @@ module ActionMailer # # Sending attachment in emails is easy: # - # class ApplicationMailer < ActionMailer::Base + # class NotifierMailer < ApplicationMailer # def welcome(recipient) # attachments['free_book.pdf'] = File.read('path/to/file.pdf') # mail(to: recipient, subject: "New account information") @@ -185,7 +200,7 @@ module ActionMailer # If you need to send attachments with no content, you need to create an empty view for it, # or add an empty body parameter like this: # - # class ApplicationMailer < ActionMailer::Base + # class NotifierMailer < ApplicationMailer # def welcome(recipient) # attachments['free_book.pdf'] = File.read('path/to/file.pdf') # mail(to: recipient, subject: "New account information", body: "") @@ -197,7 +212,7 @@ module ActionMailer # You can also specify that a file should be displayed inline with other HTML. This is useful # if you want to display a corporate logo or a photo. # - # class ApplicationMailer < ActionMailer::Base + # class NotifierMailer < ApplicationMailer # def welcome(recipient) # attachments.inline['photo.png'] = File.read('path/to/photo.png') # mail(to: recipient, subject: "Here is what we look like") @@ -236,7 +251,7 @@ module ActionMailer # Action Mailer provides some intelligent defaults for your emails, these are usually specified in a # default method inside the class definition: # - # class Notifier < ActionMailer::Base + # class NotifierMailer < ApplicationMailer # default sender: 'system@example.com' # end # @@ -244,8 +259,8 @@ module ActionMailer # <tt>ActionMailer::Base</tt> sets the following: # # * <tt>mime_version: "1.0"</tt> - # * <tt>charset: "UTF-8",</tt> - # * <tt>content_type: "text/plain",</tt> + # * <tt>charset: "UTF-8"</tt> + # * <tt>content_type: "text/plain"</tt> # * <tt>parts_order: [ "text/plain", "text/enriched", "text/html" ]</tt> # # <tt>parts_order</tt> and <tt>charset</tt> are not actually valid <tt>Mail::Message</tt> header fields, @@ -254,7 +269,7 @@ module ActionMailer # As you can pass in any header, you need to either quote the header as a string, or pass it in as # an underscored symbol, so the following will work: # - # class Notifier < ActionMailer::Base + # class NotifierMailer < ApplicationMailer # default 'Content-Transfer-Encoding' => '7bit', # content_description: 'This is a description' # end @@ -262,7 +277,7 @@ module ActionMailer # Finally, Action Mailer also supports passing <tt>Proc</tt> objects into the default hash, so you # can define methods that evaluate as the message is being generated: # - # class Notifier < ActionMailer::Base + # class NotifierMailer < ApplicationMailer # default 'X-Special-Header' => Proc.new { my_method } # # private @@ -273,7 +288,7 @@ module ActionMailer # end # # Note that the proc is evaluated right at the start of the mail message generation, so if you - # set something in the defaults using a proc, and then set the same thing inside of your + # set something in the default using a proc, and then set the same thing inside of your # mailer method, it will get over written by the mailer method. # # It is also possible to set these default options that will be used in all mailers through @@ -287,7 +302,7 @@ module ActionMailer # This may be useful, for example, when you want to add default inline attachments for all # messages sent out by a certain mailer class: # - # class Notifier < ActionMailer::Base + # class NotifierMailer < ApplicationMailer # before_action :add_inline_attachment! # # def welcome @@ -306,8 +321,9 @@ module ActionMailer # callbacks in the same manner that you would use callbacks in classes that # inherit from <tt>ActionController::Base</tt>. # - # Note that unless you have a specific reason to do so, you should prefer using before_action - # rather than after_action in your Action Mailer classes so that headers are parsed properly. + # Note that unless you have a specific reason to do so, you should prefer + # using <tt>before_action</tt> rather than <tt>after_action</tt> in your + # Action Mailer classes so that headers are parsed properly. # # = Previewing emails # @@ -315,15 +331,15 @@ module ActionMailer # <tt>ActionMailer::Base.preview_path</tt>. Since most emails do something interesting # with database data, you'll need to write some scenarios to load messages with fake data: # - # class NotifierPreview < ActionMailer::Preview + # class NotifierMailerPreview < ActionMailer::Preview # def welcome - # Notifier.welcome(User.first) + # NotifierMailer.welcome(User.first) # end # end # # Methods must return a <tt>Mail::Message</tt> object which can be generated by calling the mailer - # method without the additional <tt>deliver</tt>. The location of the mailer previews - # directory can be configured using the <tt>preview_path</tt> option which has a default + # method without the additional <tt>deliver_now</tt> / <tt>deliver_later</tt>. The location of the + # mailer previews directory can be configured using the <tt>preview_path</tt> option which has a default # of <tt>test/mailers/previews</tt>: # # config.action_mailer.preview_path = "#{Rails.root}/lib/mailer_previews" @@ -366,8 +382,8 @@ module ActionMailer # * <tt>:password</tt> - If your mail server requires authentication, set the password in this setting. # * <tt>:authentication</tt> - If your mail server requires authentication, you need to specify the # authentication type here. - # This is a symbol and one of <tt>:plain</tt> (will send the password in the clear), <tt>:login</tt> (will - # send password Base64 encoded) or <tt>:cram_md5</tt> (combines a Challenge/Response mechanism to exchange + # This is a symbol and one of <tt>:plain</tt> (will send the password Base64 encoded), <tt>:login</tt> (will + # send the password Base64 encoded) or <tt>:cram_md5</tt> (combines a Challenge/Response mechanism to exchange # information and a cryptographic Message Digest 5 algorithm to hash important information) # * <tt>:enable_starttls_auto</tt> - Detects if STARTTLS is enabled in your SMTP server and starts # to use it. Defaults to <tt>true</tt>. @@ -399,6 +415,8 @@ module ActionMailer # # * <tt>deliveries</tt> - Keeps an array of all the emails sent out through the Action Mailer with # <tt>delivery_method :test</tt>. Most useful for unit and functional testing. + # + # * <tt>deliver_later_queue_name</tt> - The name of the queue used with <tt>deliver_later</tt>. class Base < AbstractController::Base include DeliveryMethods include Previews @@ -483,7 +501,7 @@ module ActionMailer # Sets the defaults through app configuration: # - # config.action_mailer.default { from: "no-reply@example.org" } + # config.action_mailer.default(from: "no-reply@example.org") # # Aliased by ::default_options= def default(value = nil) @@ -548,8 +566,8 @@ module ActionMailer end def method_missing(method_name, *args) # :nodoc: - if respond_to?(method_name) - new(method_name, *args).message + if action_methods.include?(method_name.to_s) + MessageDelivery.new(self, method_name, *args) else super end @@ -576,8 +594,6 @@ module ActionMailer } ActiveSupport::Notifications.instrument("process.action_mailer", payload) do - lookup_context.skip_default_locale! - super @_message = NullMail.new unless @_mail_was_called end @@ -585,6 +601,11 @@ module ActionMailer class NullMail #:nodoc: def body; '' end + def header; {} end + + def respond_to?(string, include_all=false) + true + end def method_missing(*args) nil @@ -610,6 +631,26 @@ module ActionMailer # The resulting <tt>Mail::Message</tt> will have the following in its header: # # X-Special-Domain-Specific-Header: SecretValue + # + # Note about replacing already defined headers: + # + # * +subject+ + # * +sender+ + # * +from+ + # * +to+ + # * +cc+ + # * +bcc+ + # * +reply-to+ + # * +orig-date+ + # * +message-id+ + # * +references+ + # + # Fields can only appear once in email headers while other fields such as + # <tt>X-Anything</tt> can appear multiple times. + # + # If you want to replace any header which already exists, first set it to + # +nil+ in order to reset the value otherwise another field will be added + # for the same header. def headers(args = nil) if args @_message.headers(args) @@ -670,8 +711,8 @@ module ActionMailer # The main method that creates the message and renders the email templates. There are # two ways to call this method, with a block, or without a block. # - # Both methods accept a headers hash. This hash allows you to specify the most used headers - # in an email message, these are: + # It accepts a headers hash. This hash allows you to specify + # the most used headers in an email message, these are: # # * +:subject+ - The subject of the message, if this is omitted, Action Mailer will # ask the Rails I18n class for a translated +:subject+ in the scope of @@ -760,7 +801,6 @@ module ActionMailer def mail(headers = {}, &block) return @_message if @_mail_was_called && headers.blank? && !block - @_mail_was_called = true m = @_message # At the beginning, do not consider class default for content_type @@ -782,12 +822,14 @@ module ActionMailer # Set configure delivery behavior wrap_delivery_behavior!(headers.delete(:delivery_method), headers.delete(:delivery_method_options)) - # Assign all headers except parts_order, content_type and body + # Assign all headers except parts_order, content_type, body, template_name, and template_path assignable = headers.except(:parts_order, :content_type, :body, :template_name, :template_path) assignable.each { |k, v| m[k] = v } # Render the templates and blocks responses = collect_responses(headers, &block) + @_mail_was_called = true + create_parts_from_responses(m, responses) # Setup content type, reapply charset and handle parts order @@ -819,7 +861,7 @@ module ActionMailer when user_content_type.present? user_content_type when m.has_attachments? - if m.attachments.detect { |a| a.inline? } + if m.attachments.detect(&:inline?) ["multipart", "related", params] else ["multipart", "mixed", params] @@ -874,7 +916,7 @@ module ActionMailer if templates.empty? raise ActionView::MissingTemplate.new(paths, name, paths, false, 'mailer') else - templates.uniq { |t| t.formats }.each(&block) + templates.uniq(&:formats).each(&block) end end diff --git a/actionmailer/lib/action_mailer/delivery_job.rb b/actionmailer/lib/action_mailer/delivery_job.rb new file mode 100644 index 0000000000..52772af2d3 --- /dev/null +++ b/actionmailer/lib/action_mailer/delivery_job.rb @@ -0,0 +1,13 @@ +require 'active_job' + +module ActionMailer + # The <tt>ActionMailer::DeliveryJob</tt> class is used when you + # want to send emails outside of the request-response cycle. + class DeliveryJob < ActiveJob::Base # :nodoc: + queue_as { ActionMailer::Base.deliver_later_queue_name } + + def perform(mailer, mail_method, delivery_method, *args) #:nodoc: + mailer.constantize.public_send(mail_method, *args).send(delivery_method) + end + end +end diff --git a/actionmailer/lib/action_mailer/delivery_methods.rb b/actionmailer/lib/action_mailer/delivery_methods.rb index aedcd81e52..4758b55a2a 100644 --- a/actionmailer/lib/action_mailer/delivery_methods.rb +++ b/actionmailer/lib/action_mailer/delivery_methods.rb @@ -16,6 +16,9 @@ module ActionMailer cattr_accessor :perform_deliveries self.perform_deliveries = true + cattr_accessor :deliver_later_queue_name + self.deliver_later_queue_name = :mailers + self.delivery_methods = {}.freeze self.delivery_method = :smtp diff --git a/actionmailer/lib/action_mailer/gem_version.rb b/actionmailer/lib/action_mailer/gem_version.rb index b564813ccf..b35d2ed965 100644 --- a/actionmailer/lib/action_mailer/gem_version.rb +++ b/actionmailer/lib/action_mailer/gem_version.rb @@ -1,12 +1,12 @@ module ActionMailer - # Returns the version of the currently loaded ActionMailer as a <tt>Gem::Version</tt> + # Returns the version of the currently loaded Action Mailer as a <tt>Gem::Version</tt>. def self.gem_version Gem::Version.new VERSION::STRING end module VERSION - MAJOR = 4 - MINOR = 2 + MAJOR = 5 + MINOR = 0 TINY = 0 PRE = "alpha" diff --git a/actionmailer/lib/action_mailer/inline_preview_interceptor.rb b/actionmailer/lib/action_mailer/inline_preview_interceptor.rb new file mode 100644 index 0000000000..6d02b39225 --- /dev/null +++ b/actionmailer/lib/action_mailer/inline_preview_interceptor.rb @@ -0,0 +1,61 @@ +require 'base64' + +module ActionMailer + # Implements a mailer preview interceptor that converts image tag src attributes + # that use inline cid: style urls to data: style urls so that they are visible + # when previewing a HTML email in a web browser. + # + # This interceptor is enabled by default. To disable it, delete it from the + # <tt>ActionMailer::Base.preview_interceptors</tt> array: + # + # ActionMailer::Base.preview_interceptors.delete(ActionMailer::InlinePreviewInterceptor) + # + class InlinePreviewInterceptor + PATTERN = /src=(?:"cid:[^"]+"|'cid:[^']+')/i + + include Base64 + + def self.previewing_email(message) #:nodoc: + new(message).transform! + end + + def initialize(message) #:nodoc: + @message = message + end + + def transform! #:nodoc: + return message if html_part.blank? + + html_source.gsub!(PATTERN) do |match| + if part = find_part(match[9..-2]) + %[src="#{data_url(part)}"] + else + match + end + end + + message + end + + private + def message + @message + end + + def html_part + @html_part ||= message.html_part + end + + def html_source + html_part.body.raw_source + end + + def data_url(part) + "data:#{part.mime_type};base64,#{strict_encode64(part.body.raw_source)}" + end + + def find_part(cid) + message.all_parts.find{ |p| p.attachment? && p.cid == cid } + end + end +end diff --git a/actionmailer/lib/action_mailer/log_subscriber.rb b/actionmailer/lib/action_mailer/log_subscriber.rb index 5b57c75ec3..7e9d916b66 100644 --- a/actionmailer/lib/action_mailer/log_subscriber.rb +++ b/actionmailer/lib/action_mailer/log_subscriber.rb @@ -2,7 +2,7 @@ require 'active_support/log_subscriber' module ActionMailer # Implements the ActiveSupport::LogSubscriber for logging notifications when - # email is delivered and received. + # email is delivered or received. class LogSubscriber < ActiveSupport::LogSubscriber # An email was delivered. def deliver(event) @@ -29,7 +29,7 @@ module ActionMailer end end - # Use the logger configured for ActionMailer::Base + # Use the logger configured for ActionMailer::Base. def logger ActionMailer::Base.logger end diff --git a/actionmailer/lib/action_mailer/mail_helper.rb b/actionmailer/lib/action_mailer/mail_helper.rb index 483277af04..239974e7b1 100644 --- a/actionmailer/lib/action_mailer/mail_helper.rb +++ b/actionmailer/lib/action_mailer/mail_helper.rb @@ -4,7 +4,17 @@ module ActionMailer # attachments list. module MailHelper # Take the text and format it, indented two spaces for each line, and - # wrapped at 72 columns. + # wrapped at 72 columns: + # + # text = <<-TEXT + # This is + # the paragraph. + # + # * item1 * item2 + # TEXT + # + # block_format text + # # => " This is the paragraph.\n\n * item1\n * item2\n" def block_format(text) formatted = text.split(/\n\r?\n/).collect { |paragraph| format_paragraph(paragraph) @@ -29,10 +39,12 @@ module ActionMailer # Access the message attachments list. def attachments - @_message.attachments + mailer.attachments end # Returns +text+ wrapped at +len+ columns and indented +indent+ spaces. + # By default column length +len+ equals 72 characters and indent + # +indent+ equal two spaces. # # my_text = 'Here is a sample text with more than 40 characters' # diff --git a/actionmailer/lib/action_mailer/message_delivery.rb b/actionmailer/lib/action_mailer/message_delivery.rb new file mode 100644 index 0000000000..622d481113 --- /dev/null +++ b/actionmailer/lib/action_mailer/message_delivery.rb @@ -0,0 +1,94 @@ +require 'delegate' + +module ActionMailer + + # The <tt>ActionMailer::MessageDelivery</tt> class is used by + # <tt>ActionMailer::Base</tt> when creating a new mailer. + # <tt>MessageDelivery</tt> is a wrapper (+Delegator+ subclass) around a lazy + # created <tt>Mail::Message</tt>. You can get direct access to the + # <tt>Mail::Message</tt>, deliver the email or schedule the email to be sent + # through Active Job. + # + # Notifier.welcome(User.first) # an ActionMailer::MessageDelivery object + # Notifier.welcome(User.first).deliver_now # sends the email + # Notifier.welcome(User.first).deliver_later # enqueue email delivery as a job through Active Job + # Notifier.welcome(User.first).message # a Mail::Message object + class MessageDelivery < Delegator + def initialize(mailer, mail_method, *args) #:nodoc: + @mailer = mailer + @mail_method = mail_method + @args = args + end + + def __getobj__ #:nodoc: + @obj ||= @mailer.send(:new, @mail_method, *@args).message + end + + def __setobj__(obj) #:nodoc: + @obj = obj + end + + # Returns the Mail::Message object + def message + __getobj__ + end + + # Enqueues the email to be delivered through Active Job. When the + # job runs it will send the email using +deliver_now!+. That means + # that the message will be sent bypassing checking +perform_deliveries+ + # and +raise_delivery_errors+, so use with caution. + # + # Notifier.welcome(User.first).deliver_later! + # Notifier.welcome(User.first).deliver_later!(wait: 1.hour) + # Notifier.welcome(User.first).deliver_later!(wait_until: 10.hours.from_now) + # + # Options: + # + # * <tt>:wait</tt> - Enqueue the email to be delivered with a delay + # * <tt>:wait_until</tt> - Enqueue the email to be delivered at (after) a specific date / time + # * <tt>:queue</tt> - Enqueue the email on the specified queue + def deliver_later!(options={}) + enqueue_delivery :deliver_now!, options + end + + # Enqueues the email to be delivered through Active Job. When the + # job runs it will send the email using +deliver_now+. + # + # Notifier.welcome(User.first).deliver_later + # Notifier.welcome(User.first).deliver_later(wait: 1.hour) + # Notifier.welcome(User.first).deliver_later(wait_until: 10.hours.from_now) + # + # Options: + # + # * <tt>:wait</tt> - Enqueue the email to be delivered with a delay. + # * <tt>:wait_until</tt> - Enqueue the email to be delivered at (after) a specific date / time. + # * <tt>:queue</tt> - Enqueue the email on the specified queue. + def deliver_later(options={}) + enqueue_delivery :deliver_now, options + end + + # Delivers an email without checking +perform_deliveries+ and +raise_delivery_errors+, + # so use with caution. + # + # Notifier.welcome(User.first).deliver_now! + # + def deliver_now! + message.deliver! + end + + # Delivers an email: + # + # Notifier.welcome(User.first).deliver_now + # + def deliver_now + message.deliver + end + + private + + def enqueue_delivery(delivery_method, options={}) + args = @mailer.name, @mail_method.to_s, delivery_method.to_s, *@args + ActionMailer::DeliveryJob.set(options).perform_later(*args) + end + end +end diff --git a/actionmailer/lib/action_mailer/preview.rb b/actionmailer/lib/action_mailer/preview.rb index 33de1dc049..aab92fe8db 100644 --- a/actionmailer/lib/action_mailer/preview.rb +++ b/actionmailer/lib/action_mailer/preview.rb @@ -21,8 +21,10 @@ module ActionMailer # :nodoc: mattr_accessor :preview_interceptors, instance_writer: false - self.preview_interceptors = [] + self.preview_interceptors = [ActionMailer::InlinePreviewInterceptor] + end + module ClassMethods # Register one or more Interceptors which will be called before mail is previewed. def register_preview_interceptors(*interceptors) interceptors.flatten.compact.each { |interceptor| register_preview_interceptor(interceptor) } @@ -50,7 +52,7 @@ module ActionMailer extend ActiveSupport::DescendantsTracker class << self - # Returns all mailer preview classes + # Returns all mailer preview classes. def all load_previews if descendants.empty? descendants @@ -66,27 +68,27 @@ module ActionMailer message end - # Returns all of the available email previews + # Returns all of the available email previews. def emails public_instance_methods(false).map(&:to_s).sort end - # Returns true if the email exists + # Returns true if the email exists. def email_exists?(email) emails.include?(email) end - # Returns true if the preview exists + # Returns true if the preview exists. def exists?(preview) all.any?{ |p| p.preview_name == preview } end - # Find a mailer preview by its underscored class name + # Find a mailer preview by its underscored class name. def find(preview) all.find{ |p| p.preview_name == preview } end - # Returns the underscored name of the mailer preview without the suffix + # Returns the underscored name of the mailer preview without the suffix. def preview_name name.sub(/Preview$/, '').underscore end diff --git a/actionmailer/lib/action_mailer/railtie.rb b/actionmailer/lib/action_mailer/railtie.rb index c62d4b5082..fa707021c7 100644 --- a/actionmailer/lib/action_mailer/railtie.rb +++ b/actionmailer/lib/action_mailer/railtie.rb @@ -1,3 +1,4 @@ +require 'active_job/railtie' require "action_mailer" require "rails" require "abstract_controller/railties/routes_helpers" @@ -15,6 +16,11 @@ module ActionMailer paths = app.config.paths options = app.config.action_mailer + if app.config.force_ssl + options.default_url_options ||= {} + options.default_url_options[:protocol] ||= 'https' + end + options.assets_dir ||= paths["public"].first options.javascripts_dir ||= paths["public/javascripts"].first options.stylesheets_dir ||= paths["public/stylesheets"].first @@ -40,7 +46,7 @@ module ActionMailer options.each { |k,v| send("#{k}=", v) } if options.show_previews - app.routes.append do + app.routes.prepend do get '/rails/mailers' => "rails/mailers#index" get '/rails/mailers/*path' => "rails/mailers#preview" end diff --git a/actionmailer/lib/action_mailer/test_case.rb b/actionmailer/lib/action_mailer/test_case.rb index a5442c0316..0aa15e31ba 100644 --- a/actionmailer/lib/action_mailer/test_case.rb +++ b/actionmailer/lib/action_mailer/test_case.rb @@ -1,4 +1,5 @@ require 'active_support/test_case' +require 'rails-dom-testing' module ActionMailer class NonInferrableMailerError < ::StandardError @@ -15,6 +16,8 @@ module ActionMailer include ActiveSupport::Testing::ConstantLookup include TestHelper + include Rails::Dom::Testing::Assertions::SelectorAssertions + include Rails::Dom::Testing::Assertions::DomAssertions included do class_attribute :_mailer_class @@ -54,20 +57,28 @@ module ActionMailer protected - def initialize_test_deliveries - @old_delivery_method = ActionMailer::Base.delivery_method + def initialize_test_deliveries # :nodoc: + set_delivery_method :test @old_perform_deliveries = ActionMailer::Base.perform_deliveries - ActionMailer::Base.delivery_method = :test ActionMailer::Base.perform_deliveries = true end - def restore_test_deliveries - ActionMailer::Base.delivery_method = @old_delivery_method + def restore_test_deliveries # :nodoc: + restore_delivery_method ActionMailer::Base.perform_deliveries = @old_perform_deliveries ActionMailer::Base.deliveries.clear end - def set_expected_mail + def set_delivery_method(method) # :nodoc: + @old_delivery_method = ActionMailer::Base.delivery_method + ActionMailer::Base.delivery_method = method + end + + def restore_delivery_method # :nodoc: + ActionMailer::Base.delivery_method = @old_delivery_method + end + + def set_expected_mail # :nodoc: @expected = Mail.new @expected.content_type ["text", "plain", { "charset" => charset }] @expected.mime_version = '1.0' diff --git a/actionmailer/lib/action_mailer/test_helper.rb b/actionmailer/lib/action_mailer/test_helper.rb index 06da0dd27e..45cfe16899 100644 --- a/actionmailer/lib/action_mailer/test_helper.rb +++ b/actionmailer/lib/action_mailer/test_helper.rb @@ -1,14 +1,18 @@ +require 'active_job' + module ActionMailer # Provides helper methods for testing Action Mailer, including #assert_emails - # and #assert_no_emails + # and #assert_no_emails. module TestHelper + include ActiveJob::TestHelper + # Asserts that the number of emails sent matches the given number. # # def test_emails # assert_emails 0 - # ContactMailer.welcome.deliver + # ContactMailer.welcome.deliver_now # assert_emails 1 - # ContactMailer.welcome.deliver + # ContactMailer.welcome.deliver_now # assert_emails 2 # end # @@ -17,12 +21,12 @@ module ActionMailer # # def test_emails_again # assert_emails 1 do - # ContactMailer.welcome.deliver + # ContactMailer.welcome.deliver_now # end # # assert_emails 2 do - # ContactMailer.welcome.deliver - # ContactMailer.welcome.deliver + # ContactMailer.welcome.deliver_now + # ContactMailer.welcome.deliver_now # end # end def assert_emails(number) @@ -30,7 +34,7 @@ module ActionMailer original_count = ActionMailer::Base.deliveries.size yield new_count = ActionMailer::Base.deliveries.size - assert_equal original_count + number, new_count, "#{number} emails expected, but #{new_count - original_count} were sent" + assert_equal number, new_count - original_count, "#{number} emails expected, but #{new_count - original_count} were sent" else assert_equal number, ActionMailer::Base.deliveries.size end @@ -40,7 +44,7 @@ module ActionMailer # # def test_emails # assert_no_emails - # ContactMailer.welcome.deliver + # ContactMailer.welcome.deliver_now # assert_emails 1 # end # @@ -58,5 +62,52 @@ module ActionMailer def assert_no_emails(&block) assert_emails 0, &block end + + # Asserts that the number of emails enqueued for later delivery matches + # the given number. + # + # def test_emails + # assert_enqueued_emails 0 + # ContactMailer.welcome.deliver_later + # assert_enqueued_emails 1 + # ContactMailer.welcome.deliver_later + # assert_enqueued_emails 2 + # end + # + # If a block is passed, that block should cause the specified number of + # emails to be enqueued. + # + # def test_emails_again + # assert_enqueued_emails 1 do + # ContactMailer.welcome.deliver_later + # end + # + # assert_enqueued_emails 2 do + # ContactMailer.welcome.deliver_later + # ContactMailer.welcome.deliver_later + # end + # end + def assert_enqueued_emails(number, &block) + assert_enqueued_jobs number, only: ActionMailer::DeliveryJob, &block + end + + # Asserts that no emails are enqueued for later delivery. + # + # def test_no_emails + # assert_no_enqueued_emails + # ContactMailer.welcome.deliver_later + # assert_enqueued_emails 1 + # end + # + # If a block is provided, it should not cause any emails to be enqueued. + # + # def test_no_emails + # assert_no_enqueued_emails do + # # No emails should be enqueued from this block + # end + # end + def assert_no_enqueued_emails(&block) + assert_no_enqueued_jobs only: ActionMailer::DeliveryJob, &block + end end end diff --git a/actionmailer/lib/rails/generators/mailer/USAGE b/actionmailer/lib/rails/generators/mailer/USAGE index 323bb8a87f..2b0a078109 100644 --- a/actionmailer/lib/rails/generators/mailer/USAGE +++ b/actionmailer/lib/rails/generators/mailer/USAGE @@ -11,7 +11,7 @@ Example: rails generate mailer Notifications signup forgot_password invoice creates a Notifications mailer class, views, and test: - Mailer: app/mailers/notifications.rb - Views: app/views/notifications/signup.text.erb [...] - Test: test/mailers/notifications_test.rb + Mailer: app/mailers/notifications_mailer.rb + Views: app/views/notifications_mailer/signup.text.erb [...] + Test: test/mailers/notifications_mailer_test.rb diff --git a/actionmailer/lib/rails/generators/mailer/mailer_generator.rb b/actionmailer/lib/rails/generators/mailer/mailer_generator.rb index d5bf864595..3ec7d3d896 100644 --- a/actionmailer/lib/rails/generators/mailer/mailer_generator.rb +++ b/actionmailer/lib/rails/generators/mailer/mailer_generator.rb @@ -4,13 +4,22 @@ module Rails source_root File.expand_path("../templates", __FILE__) argument :actions, type: :array, default: [], banner: "method method" - check_class_collision + + check_class_collision suffix: "Mailer" def create_mailer_file - template "mailer.rb", File.join('app/mailers', class_path, "#{file_name}.rb") + template "mailer.rb", File.join('app/mailers', class_path, "#{file_name}_mailer.rb") + if self.behavior == :invoke + template "application_mailer.rb", 'app/mailers/application_mailer.rb' + end end hook_for :template_engine, :test_framework + + protected + def file_name + @_file_name ||= super.gsub(/\_mailer/i, '') + end end end end diff --git a/actionmailer/lib/rails/generators/mailer/templates/application_mailer.rb b/actionmailer/lib/rails/generators/mailer/templates/application_mailer.rb new file mode 100644 index 0000000000..d25d8892dd --- /dev/null +++ b/actionmailer/lib/rails/generators/mailer/templates/application_mailer.rb @@ -0,0 +1,4 @@ +class ApplicationMailer < ActionMailer::Base + default from: "from@example.com" + layout 'mailer' +end diff --git a/actionmailer/lib/rails/generators/mailer/templates/mailer.rb b/actionmailer/lib/rails/generators/mailer/templates/mailer.rb index edcfb4233d..348d314758 100644 --- a/actionmailer/lib/rails/generators/mailer/templates/mailer.rb +++ b/actionmailer/lib/rails/generators/mailer/templates/mailer.rb @@ -1,12 +1,11 @@ <% module_namespacing do -%> -class <%= class_name %> < ActionMailer::Base - default from: "from@example.com" +class <%= class_name %>Mailer < ApplicationMailer <% actions.each do |action| -%> # Subject can be set in your I18n file at config/locales/en.yml # with the following lookup: # - # en.<%= file_path.tr("/",".") %>.<%= action %>.subject + # en.<%= file_path.tr("/",".") %>_mailer.<%= action %>.subject # def <%= action %> @greeting = "Hi" diff --git a/actionmailer/test/abstract_unit.rb b/actionmailer/test/abstract_unit.rb index 98d266bd73..85d3629514 100644 --- a/actionmailer/test/abstract_unit.rb +++ b/actionmailer/test/abstract_unit.rb @@ -9,13 +9,13 @@ silence_warnings do end require 'active_support/testing/autorun' +require 'active_support/testing/method_call_assertions' require 'action_mailer' require 'action_mailer/test_case' -require 'mail' # Emulate AV railtie require 'action_view' -ActionMailer::Base.send(:include, ActionView::Layouts) +ActionMailer::Base.include(ActionView::Layouts) # Show backtraces for deprecated behavior for quicker cleanup. ActiveSupport::Deprecation.debug = true @@ -26,21 +26,12 @@ I18n.enforce_available_locales = false FIXTURE_LOAD_PATH = File.expand_path('fixtures', File.dirname(__FILE__)) ActionMailer::Base.view_paths = FIXTURE_LOAD_PATH -class Rails +module Rails def self.root File.expand_path('../', File.dirname(__FILE__)) end end -def set_delivery_method(method) - @old_delivery_method = ActionMailer::Base.delivery_method - ActionMailer::Base.delivery_method = method -end - -def restore_delivery_method - ActionMailer::Base.delivery_method = @old_delivery_method -end - # Skips the current run on Rubinius using Minitest::Assertions#skip def rubinius_skip(message = '') skip message if RUBY_ENGINE == 'rbx' @@ -50,4 +41,6 @@ def jruby_skip(message = '') skip message if defined?(JRUBY_VERSION) end -require 'mocha/setup' # FIXME: stop using mocha +class ActiveSupport::TestCase + include ActiveSupport::Testing::MethodCallAssertions +end diff --git a/actionmailer/test/assert_select_email_test.rb b/actionmailer/test/assert_select_email_test.rb new file mode 100644 index 0000000000..cae2e20abd --- /dev/null +++ b/actionmailer/test/assert_select_email_test.rb @@ -0,0 +1,47 @@ +require 'abstract_unit' + +class AssertSelectEmailTest < ActionMailer::TestCase + class AssertSelectMailer < ActionMailer::Base + def test(html) + mail body: html, content_type: "text/html", + subject: "Test e-mail", from: "test@test.host", to: "test <test@test.host>" + end + end + + class AssertMultipartSelectMailer < ActionMailer::Base + def test(options) + mail subject: "Test e-mail", from: "test@test.host", to: "test <test@test.host>" do |format| + format.text { render text: options[:text] } + format.html { render text: options[:html] } + end + end + end + + # + # Test assert_select_email + # + + def test_assert_select_email + assert_raise ActiveSupport::TestCase::Assertion do + assert_select_email {} + end + + AssertSelectMailer.test("<div><p>foo</p><p>bar</p></div>").deliver_now + assert_select_email do + assert_select "div:root" do + assert_select "p:first-child", "foo" + assert_select "p:last-child", "bar" + end + end + end + + def test_assert_select_email_multipart + AssertMultipartSelectMailer.test(html: "<div><p>foo</p><p>bar</p></div>", text: 'foo bar').deliver_now + assert_select_email do + assert_select "div:root" do + assert_select "p:first-child", "foo" + assert_select "p:last-child", "bar" + end + end + end +end diff --git a/actionmailer/test/asset_host_test.rb b/actionmailer/test/asset_host_test.rb index 9ba67c2842..10cfdcf693 100644 --- a/actionmailer/test/asset_host_test.rb +++ b/actionmailer/test/asset_host_test.rb @@ -9,11 +9,8 @@ class AssetHostMailer < ActionMailer::Base end end -class AssetHostTest < ActiveSupport::TestCase +class AssetHostTest < ActionMailer::TestCase def setup - set_delivery_method :test - ActionMailer::Base.perform_deliveries = true - ActionMailer::Base.deliveries.clear AssetHostMailer.configure do |c| c.asset_host = "http://www.example.com" end @@ -25,7 +22,7 @@ class AssetHostTest < ActiveSupport::TestCase def test_asset_host_as_string mail = AssetHostMailer.email_with_asset - assert_equal %Q{<img alt="Somelogo" src="http://www.example.com/images/somelogo.png" />}, mail.body.to_s.strip + assert_dom_equal %Q{<img alt="Somelogo" src="http://www.example.com/images/somelogo.png" />}, mail.body.to_s.strip end def test_asset_host_as_one_argument_proc @@ -35,6 +32,6 @@ class AssetHostTest < ActiveSupport::TestCase end } mail = AssetHostMailer.email_with_asset - assert_equal %Q{<img alt="Somelogo" src="http://images.example.com/images/somelogo.png" />}, mail.body.to_s.strip + assert_dom_equal %Q{<img alt="Somelogo" src="http://images.example.com/images/somelogo.png" />}, mail.body.to_s.strip end end diff --git a/actionmailer/test/base_test.rb b/actionmailer/test/base_test.rb index 6116d1e29f..50f2c71737 100644 --- a/actionmailer/test/base_test.rb +++ b/actionmailer/test/base_test.rb @@ -1,4 +1,3 @@ -# encoding: utf-8 require 'abstract_unit' require 'set' @@ -10,7 +9,11 @@ require 'mailers/proc_mailer' require 'mailers/asset_mailer' class BaseTest < ActiveSupport::TestCase + include Rails::Dom::Testing::Assertions::DomAssertions + setup do + @original_delivery_method = ActionMailer::Base.delivery_method + ActionMailer::Base.delivery_method = :test @original_asset_host = ActionMailer::Base.asset_host @original_assets_dir = ActionMailer::Base.assets_dir end @@ -19,6 +22,7 @@ class BaseTest < ActiveSupport::TestCase ActionMailer::Base.asset_host = @original_asset_host ActionMailer::Base.assets_dir = @original_assets_dir BaseMailer.deliveries.clear + ActionMailer::Base.delivery_method = @original_delivery_method end test "method call to mail does not raise error" do @@ -240,7 +244,7 @@ class BaseTest < ActiveSupport::TestCase end end - e = assert_raises(RuntimeError) { LateAttachmentMailer.welcome } + e = assert_raises(RuntimeError) { LateAttachmentMailer.welcome.message } assert_match(/Can't add attachments after `mail` was called./, e.message) end @@ -252,10 +256,24 @@ class BaseTest < ActiveSupport::TestCase end end - e = assert_raises(RuntimeError) { LateInlineAttachmentMailer.welcome } + e = assert_raises(RuntimeError) { LateInlineAttachmentMailer.welcome.message } assert_match(/Can't add attachments after `mail` was called./, e.message) end + test "adding inline attachments while rendering mail works" do + class LateInlineAttachmentMailer < ActionMailer::Base + def on_render + mail from: "welcome@example.com", to: "to@example.com" + end + end + + mail = LateInlineAttachmentMailer.on_render + assert_nothing_raised { mail.message } + + assert_equal ["image/jpeg; filename=controller_attachments.jpg", + "image/jpeg; filename=attachments.jpg"], mail.attachments.inline.map {|a| a['Content-Type'].to_s } + end + test "accessing attachments works after mail was called" do class LateAttachmentAccessorMailer < ActionMailer::Base def welcome @@ -268,7 +286,7 @@ class BaseTest < ActiveSupport::TestCase end end - assert_nothing_raised { LateAttachmentAccessorMailer.welcome } + assert_nothing_raised { LateAttachmentAccessorMailer.welcome.message } end # Implicit multipart @@ -334,10 +352,35 @@ class BaseTest < ActiveSupport::TestCase assert_equal("text/plain", email.parts[0].mime_type) assert_equal("Implicit with locale PL TEXT", email.parts[0].body.encoded) assert_equal("text/html", email.parts[1].mime_type) - assert_equal("Implicit with locale HTML", email.parts[1].body.encoded) + assert_equal("Implicit with locale EN HTML", email.parts[1].body.encoded) end end + test "implicit multipart with fallback locale" do + fallback_backend = Class.new(I18n::Backend::Simple) do + include I18n::Backend::Fallbacks + end + + begin + backend = I18n.backend + I18n.backend = fallback_backend.new + I18n.fallbacks[:"de-AT"] = [:de] + + swap I18n, locale: 'de-AT' do + email = BaseMailer.implicit_with_locale + assert_equal(2, email.parts.size) + assert_equal("multipart/alternative", email.mime_type) + assert_equal("text/plain", email.parts[0].mime_type) + assert_equal("Implicit with locale DE-AT TEXT", email.parts[0].body.encoded) + assert_equal("text/html", email.parts[1].mime_type) + assert_equal("Implicit with locale DE HTML", email.parts[1].body.encoded) + end + ensure + I18n.backend = backend + end + end + + test "implicit multipart with several view paths uses the first one with template" do old = BaseMailer.view_paths begin @@ -406,6 +449,13 @@ class BaseTest < ActiveSupport::TestCase assert_equal("Format with any!", email.parts[1].body.encoded) end + test 'explicit without specifying format with format.any' do + error = assert_raises(ArgumentError) do + BaseMailer.explicit_without_specifying_format_with_any.parts + end + assert_equal "You have to supply at least one format", error.message + end + test "explicit multipart with format(Hash)" do email = BaseMailer.explicit_multipart_with_options(true) email.ready_to_send! @@ -462,55 +512,57 @@ class BaseTest < ActiveSupport::TestCase end test "calling deliver on the action should deliver the mail object" do - BaseMailer.expects(:deliver_mail).once - mail = BaseMailer.welcome.deliver - assert_equal 'The first email on new API!', mail.subject + assert_called(BaseMailer, :deliver_mail) do + mail = BaseMailer.welcome.deliver_now + assert_equal 'The first email on new API!', mail.subject + end end test "calling deliver on the action should increment the deliveries collection if using the test mailer" do - BaseMailer.delivery_method = :test - BaseMailer.welcome.deliver + BaseMailer.welcome.deliver_now assert_equal(1, BaseMailer.deliveries.length) end test "calling deliver, ActionMailer should yield back to mail to let it call :do_delivery on itself" do mail = Mail::Message.new - mail.expects(:do_delivery).once - BaseMailer.expects(:welcome).returns(mail) - BaseMailer.welcome.deliver + assert_called(mail, :do_delivery) do + assert_called(BaseMailer, :welcome, returns: mail) do + BaseMailer.welcome.deliver + end + end end # Rendering test "you can specify a different template for implicit render" do - mail = BaseMailer.implicit_different_template('implicit_multipart').deliver + mail = BaseMailer.implicit_different_template('implicit_multipart').deliver_now assert_equal("HTML Implicit Multipart", mail.html_part.body.decoded) assert_equal("TEXT Implicit Multipart", mail.text_part.body.decoded) end test "should raise if missing template in implicit render" do assert_raises ActionView::MissingTemplate do - BaseMailer.implicit_different_template('missing_template').deliver + BaseMailer.implicit_different_template('missing_template').deliver_now end assert_equal(0, BaseMailer.deliveries.length) end test "you can specify a different template for explicit render" do - mail = BaseMailer.explicit_different_template('explicit_multipart_templates').deliver + mail = BaseMailer.explicit_different_template('explicit_multipart_templates').deliver_now assert_equal("HTML Explicit Multipart Templates", mail.html_part.body.decoded) assert_equal("TEXT Explicit Multipart Templates", mail.text_part.body.decoded) end test "you can specify a different layout" do - mail = BaseMailer.different_layout('different_layout').deliver + mail = BaseMailer.different_layout('different_layout').deliver_now assert_equal("HTML -- HTML", mail.html_part.body.decoded) assert_equal("PLAIN -- PLAIN", mail.text_part.body.decoded) end test "you can specify the template path for implicit lookup" do - mail = BaseMailer.welcome_from_another_path('another.path/base_mailer').deliver + mail = BaseMailer.welcome_from_another_path('another.path/base_mailer').deliver_now assert_equal("Welcome from another path", mail.body.encoded) - mail = BaseMailer.welcome_from_another_path(['unknown/invalid', 'another.path/base_mailer']).deliver + mail = BaseMailer.welcome_from_another_path(['unknown/invalid', 'another.path/base_mailer']).deliver_now assert_equal("Welcome from another path", mail.body.encoded) end @@ -520,7 +572,7 @@ class BaseTest < ActiveSupport::TestCase mail = AssetMailer.welcome - assert_equal(%{<img alt="Dummy" src="http://global.com/images/dummy.png" />}, mail.body.to_s.strip) + assert_dom_equal(%{<img alt="Dummy" src="http://global.com/images/dummy.png" />}, mail.body.to_s.strip) end test "assets tags should use a Mailer's asset_host settings when available" do @@ -534,19 +586,19 @@ class BaseTest < ActiveSupport::TestCase mail = TempAssetMailer.welcome - assert_equal(%{<img alt="Dummy" src="http://local.com/images/dummy.png" />}, mail.body.to_s.strip) + assert_dom_equal(%{<img alt="Dummy" src="http://local.com/images/dummy.png" />}, mail.body.to_s.strip) end test 'the view is not rendered when mail was never called' do mail = BaseMailer.without_mail_call assert_equal('', mail.body.to_s.strip) - mail.deliver + mail.deliver_now end test 'the return value of mailer methods is not relevant' do mail = BaseMailer.with_nil_as_return_value assert_equal('Welcome', mail.body.to_s.strip) - mail.deliver + mail.deliver_now end # Before and After hooks @@ -565,8 +617,9 @@ class BaseTest < ActiveSupport::TestCase mail_side_effects do ActionMailer::Base.register_observer(MyObserver) mail = BaseMailer.welcome - MyObserver.expects(:delivered_email).with(mail) - mail.deliver + assert_called_with(MyObserver, :delivered_email, [mail]) do + mail.deliver_now + end end end @@ -574,8 +627,9 @@ class BaseTest < ActiveSupport::TestCase mail_side_effects do ActionMailer::Base.register_observer("BaseTest::MyObserver") mail = BaseMailer.welcome - MyObserver.expects(:delivered_email).with(mail) - mail.deliver + assert_called_with(MyObserver, :delivered_email, [mail]) do + mail.deliver_now + end end end @@ -583,8 +637,9 @@ class BaseTest < ActiveSupport::TestCase mail_side_effects do ActionMailer::Base.register_observer(:"base_test/my_observer") mail = BaseMailer.welcome - MyObserver.expects(:delivered_email).with(mail) - mail.deliver + assert_called_with(MyObserver, :delivered_email, [mail]) do + mail.deliver_now + end end end @@ -592,9 +647,11 @@ class BaseTest < ActiveSupport::TestCase mail_side_effects do ActionMailer::Base.register_observers("BaseTest::MyObserver", MySecondObserver) mail = BaseMailer.welcome - MyObserver.expects(:delivered_email).with(mail) - MySecondObserver.expects(:delivered_email).with(mail) - mail.deliver + assert_called_with(MyObserver, :delivered_email, [mail]) do + assert_called_with(MySecondObserver, :delivered_email, [mail]) do + mail.deliver_now + end + end end end @@ -612,8 +669,9 @@ class BaseTest < ActiveSupport::TestCase mail_side_effects do ActionMailer::Base.register_interceptor(MyInterceptor) mail = BaseMailer.welcome - MyInterceptor.expects(:delivering_email).with(mail) - mail.deliver + assert_called_with(MyInterceptor, :delivering_email, [mail]) do + mail.deliver_now + end end end @@ -621,8 +679,9 @@ class BaseTest < ActiveSupport::TestCase mail_side_effects do ActionMailer::Base.register_interceptor("BaseTest::MyInterceptor") mail = BaseMailer.welcome - MyInterceptor.expects(:delivering_email).with(mail) - mail.deliver + assert_called_with(MyInterceptor, :delivering_email, [mail]) do + mail.deliver_now + end end end @@ -630,8 +689,9 @@ class BaseTest < ActiveSupport::TestCase mail_side_effects do ActionMailer::Base.register_interceptor(:"base_test/my_interceptor") mail = BaseMailer.welcome - MyInterceptor.expects(:delivering_email).with(mail) - mail.deliver + assert_called_with(MyInterceptor, :delivering_email, [mail]) do + mail.deliver_now + end end end @@ -639,18 +699,21 @@ class BaseTest < ActiveSupport::TestCase mail_side_effects do ActionMailer::Base.register_interceptors("BaseTest::MyInterceptor", MySecondInterceptor) mail = BaseMailer.welcome - MyInterceptor.expects(:delivering_email).with(mail) - MySecondInterceptor.expects(:delivering_email).with(mail) - mail.deliver + assert_called_with(MyInterceptor, :delivering_email, [mail]) do + assert_called_with(MySecondInterceptor, :delivering_email, [mail]) do + mail.deliver_now + end + end end end test "being able to put proc's into the defaults hash and they get evaluated on mail sending" do mail1 = ProcMailer.welcome['X-Proc-Method'] yesterday = 1.day.ago - Time.stubs(:now).returns(yesterday) - mail2 = ProcMailer.welcome['X-Proc-Method'] - assert(mail1.to_s.to_i > mail2.to_s.to_i) + Time.stub(:now, yesterday) do + mail2 = ProcMailer.welcome['X-Proc-Method'] + assert(mail1.to_s.to_i > mail2.to_s.to_i) + end end test 'default values which have to_proc (e.g. symbols) should not be considered procs' do @@ -835,33 +898,50 @@ class BasePreviewInterceptorsTest < ActiveSupport::TestCase test "you can register a preview interceptor to the mail object that gets passed the mail object before previewing" do ActionMailer::Base.register_preview_interceptor(MyInterceptor) mail = BaseMailer.welcome - BaseMailerPreview.any_instance.stubs(:welcome).returns(mail) - MyInterceptor.expects(:previewing_email).with(mail) - BaseMailerPreview.call(:welcome) + stub_any_instance(BaseMailerPreview) do |instance| + instance.stub(:welcome, mail) do + assert_called_with(MyInterceptor, :previewing_email, [mail]) do + BaseMailerPreview.call(:welcome) + end + end + end end test "you can register a preview interceptor using its stringified name to the mail object that gets passed the mail object before previewing" do ActionMailer::Base.register_preview_interceptor("BasePreviewInterceptorsTest::MyInterceptor") mail = BaseMailer.welcome - BaseMailerPreview.any_instance.stubs(:welcome).returns(mail) - MyInterceptor.expects(:previewing_email).with(mail) - BaseMailerPreview.call(:welcome) + stub_any_instance(BaseMailerPreview) do |instance| + instance.stub(:welcome, mail) do + assert_called_with(MyInterceptor, :previewing_email, [mail]) do + BaseMailerPreview.call(:welcome) + end + end + end end test "you can register an interceptor using its symbolized underscored name to the mail object that gets passed the mail object before previewing" do ActionMailer::Base.register_preview_interceptor(:"base_preview_interceptors_test/my_interceptor") mail = BaseMailer.welcome - BaseMailerPreview.any_instance.stubs(:welcome).returns(mail) - MyInterceptor.expects(:previewing_email).with(mail) - BaseMailerPreview.call(:welcome) + stub_any_instance(BaseMailerPreview) do |instance| + instance.stub(:welcome, mail) do + assert_called_with(MyInterceptor, :previewing_email, [mail]) do + BaseMailerPreview.call(:welcome) + end + end + end end test "you can register multiple preview interceptors to the mail object that both get passed the mail object before previewing" do ActionMailer::Base.register_preview_interceptors("BasePreviewInterceptorsTest::MyInterceptor", MySecondInterceptor) mail = BaseMailer.welcome - BaseMailerPreview.any_instance.stubs(:welcome).returns(mail) - MyInterceptor.expects(:previewing_email).with(mail) - MySecondInterceptor.expects(:previewing_email).with(mail) - BaseMailerPreview.call(:welcome) + stub_any_instance(BaseMailerPreview) do |instance| + instance.stub(:welcome, mail) do + assert_called_with(MyInterceptor, :previewing_email, [mail]) do + assert_called_with(MySecondInterceptor, :previewing_email, [mail]) do + BaseMailerPreview.call(:welcome) + end + end + end + end end end diff --git a/actionmailer/test/delivery_methods_test.rb b/actionmailer/test/delivery_methods_test.rb index a76ac6d295..d17e774092 100644 --- a/actionmailer/test/delivery_methods_test.rb +++ b/actionmailer/test/delivery_methods_test.rb @@ -1,5 +1,4 @@ require 'abstract_unit' -require 'mail' class MyCustomDelivery end @@ -103,22 +102,27 @@ class MailDeliveryTest < ActiveSupport::TestCase end test "ActionMailer should be told when Mail gets delivered" do - DeliveryMailer.expects(:deliver_mail).once - DeliveryMailer.welcome.deliver + DeliveryMailer.delivery_method = :test + assert_called(DeliveryMailer, :deliver_mail) do + DeliveryMailer.welcome.deliver_now + end end test "delivery method can be customized per instance" do - Mail::SMTP.any_instance.expects(:deliver!) - email = DeliveryMailer.welcome.deliver - assert_instance_of Mail::SMTP, email.delivery_method - email = DeliveryMailer.welcome(delivery_method: :test).deliver - assert_instance_of Mail::TestMailer, email.delivery_method + stub_any_instance(Mail::SMTP, instance: Mail::SMTP.new({})) do |instance| + assert_called(instance, :deliver!) do + email = DeliveryMailer.welcome.deliver_now + assert_instance_of Mail::SMTP, email.delivery_method + email = DeliveryMailer.welcome(delivery_method: :test).deliver_now + assert_instance_of Mail::TestMailer, email.delivery_method + end + end end test "delivery method can be customized in subclasses not changing the parent" do DeliveryMailer.delivery_method = :test assert_equal :smtp, ActionMailer::Base.delivery_method - email = DeliveryMailer.welcome.deliver + email = DeliveryMailer.welcome.deliver_now assert_instance_of Mail::TestMailer, email.delivery_method end @@ -161,24 +165,29 @@ class MailDeliveryTest < ActiveSupport::TestCase test "non registered delivery methods raises errors" do DeliveryMailer.delivery_method = :unknown - assert_raise RuntimeError do - DeliveryMailer.welcome.deliver + error = assert_raise RuntimeError do + DeliveryMailer.welcome.deliver_now end + assert_equal "Invalid delivery method :unknown", error.message end test "undefined delivery methods raises errors" do DeliveryMailer.delivery_method = nil - assert_raise RuntimeError do - DeliveryMailer.welcome.deliver + error = assert_raise RuntimeError do + DeliveryMailer.welcome.deliver_now end + assert_equal "Delivery method cannot be nil", error.message end test "does not perform deliveries if requested" do old_perform_deliveries = DeliveryMailer.perform_deliveries begin DeliveryMailer.perform_deliveries = false - Mail::Message.any_instance.expects(:deliver!).never - DeliveryMailer.welcome.deliver + stub_any_instance(Mail::Message) do |instance| + assert_not_called(instance, :deliver!) do + DeliveryMailer.welcome.deliver_now + end + end ensure DeliveryMailer.perform_deliveries = old_perform_deliveries end @@ -188,7 +197,7 @@ class MailDeliveryTest < ActiveSupport::TestCase old_perform_deliveries = DeliveryMailer.perform_deliveries begin DeliveryMailer.perform_deliveries = false - DeliveryMailer.welcome.deliver + DeliveryMailer.welcome.deliver_now assert_equal [], DeliveryMailer.deliveries ensure DeliveryMailer.perform_deliveries = old_perform_deliveries @@ -198,14 +207,14 @@ class MailDeliveryTest < ActiveSupport::TestCase test "raise errors on bogus deliveries" do DeliveryMailer.delivery_method = BogusDelivery assert_raise RuntimeError do - DeliveryMailer.welcome.deliver + DeliveryMailer.welcome.deliver_now end end test "does not increment the deliveries collection on error" do DeliveryMailer.delivery_method = BogusDelivery assert_raise RuntimeError do - DeliveryMailer.welcome.deliver + DeliveryMailer.welcome.deliver_now end assert_equal [], DeliveryMailer.deliveries end @@ -216,7 +225,7 @@ class MailDeliveryTest < ActiveSupport::TestCase DeliveryMailer.delivery_method = BogusDelivery DeliveryMailer.raise_delivery_errors = false assert_nothing_raised do - DeliveryMailer.welcome.deliver + DeliveryMailer.welcome.deliver_now end ensure DeliveryMailer.raise_delivery_errors = old_raise_delivery_errors @@ -228,7 +237,7 @@ class MailDeliveryTest < ActiveSupport::TestCase begin DeliveryMailer.delivery_method = BogusDelivery DeliveryMailer.raise_delivery_errors = false - DeliveryMailer.welcome.deliver + DeliveryMailer.welcome.deliver_now assert_equal [], DeliveryMailer.deliveries ensure DeliveryMailer.raise_delivery_errors = old_raise_delivery_errors diff --git a/actionmailer/test/fixtures/base_mailer/email_custom_layout.text.html.erb b/actionmailer/test/fixtures/base_mailer/email_custom_layout.text.html.erb deleted file mode 100644 index a2187308b6..0000000000 --- a/actionmailer/test/fixtures/base_mailer/email_custom_layout.text.html.erb +++ /dev/null @@ -1 +0,0 @@ -body_text
\ No newline at end of file diff --git a/actionmailer/test/fixtures/base_mailer/implicit_with_locale.de-AT.text.erb b/actionmailer/test/fixtures/base_mailer/implicit_with_locale.de-AT.text.erb new file mode 100644 index 0000000000..e97505fad9 --- /dev/null +++ b/actionmailer/test/fixtures/base_mailer/implicit_with_locale.de-AT.text.erb @@ -0,0 +1 @@ +Implicit with locale DE-AT TEXT
\ No newline at end of file diff --git a/actionmailer/test/fixtures/base_mailer/implicit_with_locale.de.html.erb b/actionmailer/test/fixtures/base_mailer/implicit_with_locale.de.html.erb new file mode 100644 index 0000000000..0536b5d3e2 --- /dev/null +++ b/actionmailer/test/fixtures/base_mailer/implicit_with_locale.de.html.erb @@ -0,0 +1 @@ +Implicit with locale DE HTML
\ No newline at end of file diff --git a/actionmailer/test/fixtures/base_test/late_inline_attachment_mailer/on_render.erb b/actionmailer/test/fixtures/base_test/late_inline_attachment_mailer/on_render.erb new file mode 100644 index 0000000000..6decd3bb31 --- /dev/null +++ b/actionmailer/test/fixtures/base_test/late_inline_attachment_mailer/on_render.erb @@ -0,0 +1,7 @@ +<h1>Adding an inline image while rendering</h1> + +<% controller.attachments.inline["controller_attachments.jpg"] = 'via controller.attachments.inline' %> +<%= image_tag attachments['controller_attachments.jpg'].url %> + +<% attachments.inline["attachments.jpg"] = 'via attachments.inline' %> +<%= image_tag attachments['attachments.jpg'].url %> diff --git a/actionmailer/test/fixtures/first_mailer/share.erb b/actionmailer/test/fixtures/first_mailer/share.erb deleted file mode 100644 index da43638ceb..0000000000 --- a/actionmailer/test/fixtures/first_mailer/share.erb +++ /dev/null @@ -1 +0,0 @@ -first mail diff --git a/actionmailer/test/fixtures/path.with.dots/funky_path_mailer/multipart_with_template_path_with_dots.erb b/actionmailer/test/fixtures/path.with.dots/funky_path_mailer/multipart_with_template_path_with_dots.erb deleted file mode 100644 index 2d0cd5c124..0000000000 --- a/actionmailer/test/fixtures/path.with.dots/funky_path_mailer/multipart_with_template_path_with_dots.erb +++ /dev/null @@ -1 +0,0 @@ -Have some dots. Enjoy!
\ No newline at end of file diff --git a/actionmailer/test/fixtures/second_mailer/share.erb b/actionmailer/test/fixtures/second_mailer/share.erb deleted file mode 100644 index 9a54010672..0000000000 --- a/actionmailer/test/fixtures/second_mailer/share.erb +++ /dev/null @@ -1 +0,0 @@ -second mail diff --git a/actionmailer/test/fixtures/test_mailer/_subtemplate.text.erb b/actionmailer/test/fixtures/test_mailer/_subtemplate.text.erb deleted file mode 100644 index 3b4ba35f20..0000000000 --- a/actionmailer/test/fixtures/test_mailer/_subtemplate.text.erb +++ /dev/null @@ -1 +0,0 @@ -let's go!
\ No newline at end of file diff --git a/actionmailer/test/fixtures/test_mailer/custom_templating_extension.html.haml b/actionmailer/test/fixtures/test_mailer/custom_templating_extension.html.haml deleted file mode 100644 index 8dcf9746cc..0000000000 --- a/actionmailer/test/fixtures/test_mailer/custom_templating_extension.html.haml +++ /dev/null @@ -1,6 +0,0 @@ -%p Hello there, - -%p - Mr. - = @recipient - from haml
\ No newline at end of file diff --git a/actionmailer/test/fixtures/test_mailer/custom_templating_extension.text.haml b/actionmailer/test/fixtures/test_mailer/custom_templating_extension.text.haml deleted file mode 100644 index 8dcf9746cc..0000000000 --- a/actionmailer/test/fixtures/test_mailer/custom_templating_extension.text.haml +++ /dev/null @@ -1,6 +0,0 @@ -%p Hello there, - -%p - Mr. - = @recipient - from haml
\ No newline at end of file diff --git a/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.html.erb b/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.html.erb deleted file mode 100644 index 946d99ede5..0000000000 --- a/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.html.erb +++ /dev/null @@ -1,10 +0,0 @@ -<html> - <body> - HTML formatted message to <strong><%= @recipient %></strong>. - </body> -</html> -<html> - <body> - HTML formatted message to <strong><%= @recipient %></strong>. - </body> -</html> diff --git a/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.html.erb~ b/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.html.erb~ deleted file mode 100644 index 946d99ede5..0000000000 --- a/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.html.erb~ +++ /dev/null @@ -1,10 +0,0 @@ -<html> - <body> - HTML formatted message to <strong><%= @recipient %></strong>. - </body> -</html> -<html> - <body> - HTML formatted message to <strong><%= @recipient %></strong>. - </body> -</html> diff --git a/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.ignored.erb b/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.ignored.erb deleted file mode 100644 index 6940419d47..0000000000 --- a/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.ignored.erb +++ /dev/null @@ -1 +0,0 @@ -Ignored when searching for implicitly multipart parts. diff --git a/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.rhtml.bak b/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.rhtml.bak deleted file mode 100644 index 6940419d47..0000000000 --- a/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.rhtml.bak +++ /dev/null @@ -1 +0,0 @@ -Ignored when searching for implicitly multipart parts. diff --git a/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.text.erb b/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.text.erb deleted file mode 100644 index a6c8d54cf9..0000000000 --- a/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.text.erb +++ /dev/null @@ -1,2 +0,0 @@ -Plain text to <%= @recipient %>. -Plain text to <%= @recipient %>. diff --git a/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.yaml.erb b/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.yaml.erb deleted file mode 100644 index c14348c770..0000000000 --- a/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.yaml.erb +++ /dev/null @@ -1 +0,0 @@ -yaml to: <%= @recipient %>
\ No newline at end of file diff --git a/actionmailer/test/fixtures/test_mailer/included_subtemplate.text.erb b/actionmailer/test/fixtures/test_mailer/included_subtemplate.text.erb deleted file mode 100644 index ae3cfa77e7..0000000000 --- a/actionmailer/test/fixtures/test_mailer/included_subtemplate.text.erb +++ /dev/null @@ -1 +0,0 @@ -Hey Ho, <%= render partial: "subtemplate" %>
\ No newline at end of file diff --git a/actionmailer/test/fixtures/test_mailer/multipart_alternative.html.erb b/actionmailer/test/fixtures/test_mailer/multipart_alternative.html.erb deleted file mode 100644 index 73ea14f82f..0000000000 --- a/actionmailer/test/fixtures/test_mailer/multipart_alternative.html.erb +++ /dev/null @@ -1 +0,0 @@ -<strong>foo</strong> <%= @foo %>
\ No newline at end of file diff --git a/actionmailer/test/fixtures/test_mailer/multipart_alternative.plain.erb b/actionmailer/test/fixtures/test_mailer/multipart_alternative.plain.erb deleted file mode 100644 index 779fe4c1ea..0000000000 --- a/actionmailer/test/fixtures/test_mailer/multipart_alternative.plain.erb +++ /dev/null @@ -1 +0,0 @@ -foo: <%= @foo %>
\ No newline at end of file diff --git a/actionmailer/test/fixtures/test_mailer/rxml_template.rxml b/actionmailer/test/fixtures/test_mailer/rxml_template.rxml deleted file mode 100644 index d566bd8d7c..0000000000 --- a/actionmailer/test/fixtures/test_mailer/rxml_template.rxml +++ /dev/null @@ -1,2 +0,0 @@ -xml.instruct! -xml.test
\ No newline at end of file diff --git a/actionmailer/test/fixtures/test_mailer/signed_up.html.erb b/actionmailer/test/fixtures/test_mailer/signed_up.html.erb deleted file mode 100644 index 7afe1f651c..0000000000 --- a/actionmailer/test/fixtures/test_mailer/signed_up.html.erb +++ /dev/null @@ -1,3 +0,0 @@ -Hello there, - -Mr. <%= @recipient %>
\ No newline at end of file diff --git a/actionmailer/test/fixtures/url_test_mailer/exercise_url_for.erb b/actionmailer/test/fixtures/url_test_mailer/exercise_url_for.erb new file mode 100644 index 0000000000..0322c1191e --- /dev/null +++ b/actionmailer/test/fixtures/url_test_mailer/exercise_url_for.erb @@ -0,0 +1 @@ +<%= url_for(@options) %> <%= @url %> diff --git a/actionmailer/test/i18n_with_controller_test.rb b/actionmailer/test/i18n_with_controller_test.rb index ee36b89dd6..6124ffeb52 100644 --- a/actionmailer/test/i18n_with_controller_test.rb +++ b/actionmailer/test/i18n_with_controller_test.rb @@ -17,7 +17,7 @@ end class TestController < ActionController::Base def send_mail - email = I18nTestMailer.mail_with_i18n_subject("test@localhost").deliver + email = I18nTestMailer.mail_with_i18n_subject("test@localhost").deliver_now render text: "Mail sent - Subject: #{email.subject}" end end @@ -52,10 +52,15 @@ class ActionMailerI18nWithControllerTest < ActionDispatch::IntegrationTest end def test_send_mail - Mail::SMTP.any_instance.expects(:deliver!) - with_translation 'de', email_subject: '[Anmeldung] Willkommen' do - get '/test/send_mail' - assert_equal "Mail sent - Subject: [Anmeldung] Willkommen", @response.body + stub_any_instance(Mail::SMTP, instance: Mail::SMTP.new({})) do |instance| + assert_called(instance, :deliver!) do + with_translation 'de', email_subject: '[Anmeldung] Willkommen' do + ActiveSupport::Deprecation.silence do + get '/test/send_mail' + end + assert_equal "Mail sent - Subject: [Anmeldung] Willkommen", @response.body + end + end end end diff --git a/actionmailer/test/log_subscriber_test.rb b/actionmailer/test/log_subscriber_test.rb index e7a73d6c8e..3871b16840 100644 --- a/actionmailer/test/log_subscriber_test.rb +++ b/actionmailer/test/log_subscriber_test.rb @@ -22,7 +22,7 @@ class AMLogSubscriberTest < ActionMailer::TestCase end def test_deliver_is_notified - BaseMailer.welcome.deliver + BaseMailer.welcome.deliver_now wait assert_equal(1, @logger.logged(:info).size) diff --git a/actionmailer/test/mail_helper_test.rb b/actionmailer/test/mail_helper_test.rb index 24ccaab8df..ff6b25b0c7 100644 --- a/actionmailer/test/mail_helper_test.rb +++ b/actionmailer/test/mail_helper_test.rb @@ -59,6 +59,12 @@ The second end end + def use_cache + mail_with_defaults do |format| + format.html { render(inline: "<% cache(:foo) do %>Greetings from a cache helper block<% end %>") } + end + end + protected def mail_with_defaults(&block) @@ -107,5 +113,11 @@ class MailerHelperTest < ActionMailer::TestCase TEXT assert_equal expected.gsub("\n", "\r\n"), mail.body.encoded end -end + def test_use_cache + assert_nothing_raised do + mail = HelperMailer.use_cache + assert_equal "Greetings from a cache helper block", mail.body.encoded + end + end +end diff --git a/actionmailer/test/mailers/base_mailer.rb b/actionmailer/test/mailers/base_mailer.rb index bd991e209e..8c2225ce60 100644 --- a/actionmailer/test/mailers/base_mailer.rb +++ b/actionmailer/test/mailers/base_mailer.rb @@ -80,6 +80,12 @@ class BaseMailer < ActionMailer::Base end end + def explicit_without_specifying_format_with_any(hash = {}) + mail(hash) do |format| + format.any + end + end + def explicit_multipart_with_options(include_html = false) mail do |format| format.text(content_transfer_encoding: "base64"){ render "welcome" } diff --git a/actionmailer/test/mailers/delayed_mailer.rb b/actionmailer/test/mailers/delayed_mailer.rb new file mode 100644 index 0000000000..62d4baa434 --- /dev/null +++ b/actionmailer/test/mailers/delayed_mailer.rb @@ -0,0 +1,6 @@ +class DelayedMailer < ActionMailer::Base + + def test_message(*) + mail(from: 'test-sender@test.com', to: 'test-receiver@test.com', subject: 'Test Subject', body: 'Test Body') + end +end diff --git a/actionmailer/test/message_delivery_test.rb b/actionmailer/test/message_delivery_test.rb new file mode 100644 index 0000000000..b834cdd08c --- /dev/null +++ b/actionmailer/test/message_delivery_test.rb @@ -0,0 +1,96 @@ +require 'abstract_unit' +require 'active_job' +require 'mailers/delayed_mailer' + +class MessageDeliveryTest < ActiveSupport::TestCase + include ActiveJob::TestHelper + + setup do + @previous_logger = ActiveJob::Base.logger + @previous_delivery_method = ActionMailer::Base.delivery_method + @previous_deliver_later_queue_name = ActionMailer::Base.deliver_later_queue_name + ActionMailer::Base.deliver_later_queue_name = :test_queue + ActionMailer::Base.delivery_method = :test + ActiveJob::Base.logger = Logger.new(nil) + @mail = DelayedMailer.test_message(1, 2, 3) + ActionMailer::Base.deliveries.clear + ActiveJob::Base.queue_adapter.perform_enqueued_at_jobs = true + ActiveJob::Base.queue_adapter.perform_enqueued_jobs = true + end + + teardown do + ActiveJob::Base.logger = @previous_logger + ActionMailer::Base.delivery_method = @previous_delivery_method + ActionMailer::Base.deliver_later_queue_name = @previous_deliver_later_queue_name + end + + test 'should have a message' do + assert @mail.message + end + + test 'its message should be a Mail::Message' do + assert_equal Mail::Message , @mail.message.class + end + + test 'should respond to .deliver_later' do + assert_respond_to @mail, :deliver_later + end + + test 'should respond to .deliver_later!' do + assert_respond_to @mail, :deliver_later! + end + + test 'should respond to .deliver_now' do + assert_respond_to @mail, :deliver_now + end + + test 'should respond to .deliver_now!' do + assert_respond_to @mail, :deliver_now! + end + + def test_should_enqueue_and_run_correctly_in_activejob + @mail.deliver_later! + assert_equal 1, ActionMailer::Base.deliveries.size + ensure + ActionMailer::Base.deliveries.clear + end + + test 'should enqueue the email with :deliver_now delivery method' do + assert_performed_with(job: ActionMailer::DeliveryJob, args: ['DelayedMailer', 'test_message', 'deliver_now', 1, 2, 3]) do + @mail.deliver_later + end + end + + test 'should enqueue the email with :deliver_now! delivery method' do + assert_performed_with(job: ActionMailer::DeliveryJob, args: ['DelayedMailer', 'test_message', 'deliver_now!', 1, 2, 3]) do + @mail.deliver_later! + end + end + + test 'should enqueue a delivery with a delay' do + travel_to Time.new(2004, 11, 24, 01, 04, 44) do + assert_performed_with(job: ActionMailer::DeliveryJob, at: Time.current.to_f+600.seconds, args: ['DelayedMailer', 'test_message', 'deliver_now', 1, 2, 3]) do + @mail.deliver_later wait: 600.seconds + end + end + end + + test 'should enqueue a delivery at a specific time' do + later_time = Time.now.to_f + 3600 + assert_performed_with(job: ActionMailer::DeliveryJob, at: later_time, args: ['DelayedMailer', 'test_message', 'deliver_now', 1, 2, 3]) do + @mail.deliver_later wait_until: later_time + end + end + + test 'should enqueue the job on the correct queue' do + assert_performed_with(job: ActionMailer::DeliveryJob, args: ['DelayedMailer', 'test_message', 'deliver_now', 1, 2, 3], queue: "test_queue") do + @mail.deliver_later + end + end + + test 'can override the queue when enqueuing mail' do + assert_performed_with(job: ActionMailer::DeliveryJob, args: ['DelayedMailer', 'test_message', 'deliver_now', 1, 2, 3], queue: "another_queue") do + @mail.deliver_later(queue: :another_queue) + end + end +end diff --git a/actionmailer/test/test_test.rb b/actionmailer/test/test_case_test.rb index 86fd37bea6..86fd37bea6 100644 --- a/actionmailer/test/test_test.rb +++ b/actionmailer/test/test_case_test.rb diff --git a/actionmailer/test/test_helper_test.rb b/actionmailer/test/test_helper_test.rb index 1ff08a3b6e..0a4bc75d3e 100644 --- a/actionmailer/test/test_helper_test.rb +++ b/actionmailer/test/test_helper_test.rb @@ -1,5 +1,5 @@ -# encoding: utf-8 require 'abstract_unit' +require 'active_support/testing/stream' class TestHelperMailer < ActionMailer::Base def test @@ -11,6 +11,8 @@ class TestHelperMailer < ActionMailer::Base end class TestHelperMailerTest < ActionMailer::TestCase + include ActiveSupport::Testing::Stream + def test_setup_sets_right_action_mailer_options assert_equal :test, ActionMailer::Base.delivery_method assert ActionMailer::Base.perform_deliveries @@ -48,7 +50,7 @@ class TestHelperMailerTest < ActionMailer::TestCase def test_assert_emails assert_nothing_raised do assert_emails 1 do - TestHelperMailer.test.deliver + TestHelperMailer.test.deliver_now end end end @@ -56,27 +58,27 @@ class TestHelperMailerTest < ActionMailer::TestCase def test_repeated_assert_emails_calls assert_nothing_raised do assert_emails 1 do - TestHelperMailer.test.deliver + TestHelperMailer.test.deliver_now end end assert_nothing_raised do assert_emails 2 do - TestHelperMailer.test.deliver - TestHelperMailer.test.deliver + TestHelperMailer.test.deliver_now + TestHelperMailer.test.deliver_now end end end def test_assert_emails_with_no_block assert_nothing_raised do - TestHelperMailer.test.deliver + TestHelperMailer.test.deliver_now assert_emails 1 end assert_nothing_raised do - TestHelperMailer.test.deliver - TestHelperMailer.test.deliver + TestHelperMailer.test.deliver_now + TestHelperMailer.test.deliver_now assert_emails 3 end end @@ -92,7 +94,7 @@ class TestHelperMailerTest < ActionMailer::TestCase def test_assert_emails_too_few_sent error = assert_raise ActiveSupport::TestCase::Assertion do assert_emails 2 do - TestHelperMailer.test.deliver + TestHelperMailer.test.deliver_now end end @@ -102,18 +104,84 @@ class TestHelperMailerTest < ActionMailer::TestCase def test_assert_emails_too_many_sent error = assert_raise ActiveSupport::TestCase::Assertion do assert_emails 1 do - TestHelperMailer.test.deliver - TestHelperMailer.test.deliver + TestHelperMailer.test.deliver_now + TestHelperMailer.test.deliver_now end end assert_match(/1 .* but 2/, error.message) end + def test_assert_emails_message + TestHelperMailer.test.deliver_now + error = assert_raise ActiveSupport::TestCase::Assertion do + assert_emails 2 do + TestHelperMailer.test.deliver_now + end + end + assert_match "Expected: 2", error.message + assert_match "Actual: 1", error.message + end + def test_assert_no_emails_failure error = assert_raise ActiveSupport::TestCase::Assertion do assert_no_emails do - TestHelperMailer.test.deliver + TestHelperMailer.test.deliver_now + end + end + + assert_match(/0 .* but 1/, error.message) + end + + def test_assert_enqueued_emails + assert_nothing_raised do + assert_enqueued_emails 1 do + silence_stream($stdout) do + TestHelperMailer.test.deliver_later + end + end + end + end + + def test_assert_enqueued_emails_too_few_sent + error = assert_raise ActiveSupport::TestCase::Assertion do + assert_enqueued_emails 2 do + silence_stream($stdout) do + TestHelperMailer.test.deliver_later + end + end + end + + assert_match(/2 .* but 1/, error.message) + end + + def test_assert_enqueued_emails_too_many_sent + error = assert_raise ActiveSupport::TestCase::Assertion do + assert_enqueued_emails 1 do + silence_stream($stdout) do + TestHelperMailer.test.deliver_later + TestHelperMailer.test.deliver_later + end + end + end + + assert_match(/1 .* but 2/, error.message) + end + + def test_assert_no_enqueued_emails + assert_nothing_raised do + assert_no_enqueued_emails do + TestHelperMailer.test.deliver_now + end + end + end + + def test_assert_no_enqueued_emails_failure + error = assert_raise ActiveSupport::TestCase::Assertion do + assert_no_enqueued_emails do + silence_stream($stdout) do + TestHelperMailer.test.deliver_later + end end end diff --git a/actionmailer/test/url_test.rb b/actionmailer/test/url_test.rb index 589944fa69..7928fe9542 100644 --- a/actionmailer/test/url_test.rb +++ b/actionmailer/test/url_test.rb @@ -23,9 +23,32 @@ class UrlTestMailer < ActionMailer::Base mail(to: recipient, subject: "[Signed up] Welcome #{recipient}", from: "system@loudthinking.com", date: Time.local(2004, 12, 12)) end + + def exercise_url_for(options) + @options = options + @url = url_for(@options) + mail(from: 'from@example.com', to: 'to@example.com', subject: 'subject') + end end class ActionMailerUrlTest < ActionMailer::TestCase + class DummyModel + def self.model_name + OpenStruct.new(route_key: 'dummy_model') + end + + def persisted? + false + end + + def model_name + self.class.model_name + end + + def to_model + self + end + end def encode( text, charset="UTF-8" ) quoted_printable( text, charset ) @@ -40,10 +63,47 @@ class ActionMailerUrlTest < ActionMailer::TestCase mail end + def assert_url_for(expected, options, relative = false) + expected = "http://www.basecamphq.com#{expected}" if expected.start_with?('/') && !relative + urls = UrlTestMailer.exercise_url_for(options).body.to_s.chomp.split + + assert_equal expected, urls.first + assert_equal expected, urls.second + end + def setup @recipient = 'test@localhost' end + def test_url_for + UrlTestMailer.delivery_method = :test + + AppRoutes.draw do + get ':controller(/:action(/:id))' + get '/welcome' => 'foo#bar', as: 'welcome' + get '/dummy_model' => 'foo#baz', as: 'dummy_model' + end + + # string + assert_url_for 'http://foo/', 'http://foo/' + + # symbol + assert_url_for '/welcome', :welcome + + # hash + assert_url_for '/a/b/c', controller: 'a', action: 'b', id: 'c' + assert_url_for '/a/b/c', {controller: 'a', action: 'b', id: 'c', only_path: true}, true + + # model + assert_url_for '/dummy_model', DummyModel.new + + # class + assert_url_for '/dummy_model', DummyModel + + # array + assert_url_for '/dummy_model' , [DummyModel] + end + def test_signed_up_with_url UrlTestMailer.delivery_method = :test @@ -66,13 +126,13 @@ class ActionMailerUrlTest < ActionMailer::TestCase expected.message_id = '<123@456>' created.message_id = '<123@456>' - assert_equal expected.encoded, created.encoded + assert_dom_equal expected.encoded, created.encoded - assert_nothing_raised { UrlTestMailer.signed_up_with_url(@recipient).deliver } + assert_nothing_raised { UrlTestMailer.signed_up_with_url(@recipient).deliver_now } assert_not_nil ActionMailer::Base.deliveries.first delivered = ActionMailer::Base.deliveries.first delivered.message_id = '<123@456>' - assert_equal expected.encoded, delivered.encoded + assert_dom_equal expected.encoded, delivered.encoded end end |