ruby-on-railsactionmailerruby-on-rails-4.1

Rails 4.1: access current_user in ActionMailer::Preview


Rails 4.1 has a nice way to preview mailers with ActionMailer::Preview. All of my mailers take a user parameter, and I would like to pass in current_user (from Devise) for the preview.

If I try this, it doesn't work.

class SubscriptionsMailerPreview < ActionMailer::Preview
  # Preview this email at http://localhost:3000/rails/mailers/subscriptions_mailer/new
  def new
    SubscriptionsMailer.new(current_user)
  end
end

It returns undefined local variable or method 'current_user' for #<SubscriptionsMailerPreview:0xa6d4ee4>.

I suspect this is because current_user is defined by Devise in ApplicationController, and according to the docs, ActionMailer uses AbstractController::Base. In that case, would storing current_user in a class variable be a bad idea?

Does anyone know how I can use the current_user helper in ActionMailer::Preview?


Solution

  • What would happen if you move your mailer job to the background? How would you get the current user then?

    The mailer and its preview should not know about the current_user. The mailer's job is to send the mail to a user it receives. The preview is there to visually demonstrate its behaviour.

    Create a new user in your mailer preview, and pass it to the mailer.

      def new
        user = User.create! # etc...
        SubscriptionsMailer.new(user)
      end
    

    It doesn't matter who the user is. It matters that it's a user object.

    If you want to test that the application will send a mail to the current_user, write a functional test for that.