Ruby on Rails Ruby on Rails Action Mailer, Background Jobs & Caching 1 — Questions and Answers
Question 1: What class does ApplicationMailer inherit from in Ruby on Rails?
- ActionController::Base
- ActionMailer::Base (Correct answer)
- ActionDispatch::Mailer
- ActionMailer::Controller
Correct answer: ActionMailer::Base
ApplicationMailer inherits from ActionMailer::Base, which provides all email sending functionality including delivery methods, attachments, and header defaults.
Question 2: Which method delivers an email synchronously (immediately) in Action Mailer?
- deliver_async
- deliver_immediately
- deliver_now (Correct answer)
- send_mail
Correct answer: deliver_now
deliver_now sends the email synchronously, blocking the current thread until delivery is complete.
Question 3: Where should Action Mailer view templates be stored in a Rails application?
- app/mailers/views/mailer_name/
- app/templates/mailers/
- app/views/mailer_name/ (Correct answer)
- app/mail/templates/
Correct answer: app/views/mailer_name/
Mailer views follow Rails convention and are stored in app/views/ under a folder named after the mailer class (e.g., app/views/user_mailer/).
Question 4: How do you set a default 'from' email address for all mailers in ApplicationMailer?
- config.action_mailer.default_from = 'noreply@app.com'
- default from: 'noreply@app.com' (Correct answer)
- set_default_from 'noreply@app.com'
- ActionMailer.from = 'noreply@app.com'
Correct answer: default from: 'noreply@app.com'
The default class method inside ApplicationMailer accepts a hash of header defaults, including from, reply_to, and other email headers.
Question 5: Which delivery method is configured for Action Mailer in the Rails test environment?
- :smtp
- :sendmail
- :file
- :test (Correct answer)
Correct answer: :test
The :test delivery method stores emails in ActionMailer::Base.deliveries array instead of sending them, making it easy to assert email content in tests.
Question 6: How do you schedule an email to be delivered 1 hour from now using Active Job integration?
- deliver_later(wait: 1.hour) (Correct answer)
- deliver_now(delay: 1.hour)
- schedule_at(Time.now + 1.hour)
- deliver_in(1.hour)
Correct answer: deliver_later(wait: 1.hour)
deliver_later accepts a :wait option specifying a delay duration, which tells the Active Job backend to enqueue the job for future execution.
Question 7: What is the correct way to attach a file to an email in Action Mailer?
- email.attach('report.pdf', File.read(path))
- add_attachment 'report.pdf', data: File.read(path)
- attachments['report.pdf'] = File.read(path) (Correct answer)
- attach_file path, name: 'report.pdf'
Correct answer: attachments['report.pdf'] = File.read(path)
The attachments hash in Action Mailer allows you to add attachments by assigning file content to a filename key inside your mailer method.
What class does ApplicationMailer inherit from in Ruby on Rails?