ruby 41 lines · 6 steps

Previewing Rails mailers with sample data

An ActionMailer::Preview builds throwaway in-memory records so you can view every email variant in the browser.

Explained by highlit
1class OrderMailerPreview < ActionMailer::Preview
2 def confirmation
3 OrderMailer.confirmation(sample_order)
4 end
5 
6 def shipped
7 order = sample_order
8 order.shipment = Shipment.new(
9 carrier: "UPS",
10 tracking_number: "1Z999AA10123456784",
11 estimated_delivery: 3.business_days.from_now
12 )
13 
14 OrderMailer.shipped(order)
15 end
16 
17 def refunded
18 OrderMailer.refunded(sample_order, amount: Money.new(2_499, "USD"))
19 end
20 
21 private
22 
23 def sample_order
24 Order.new(
25 id: 42,
26 number: "ORD-2024-000042",
27 placed_at: Time.current,
28 customer: Customer.new(name: "Ada Lovelace", email: "ada@example.com"),
29 line_items: [
30 LineItem.new(name: "Mechanical Keyboard", quantity: 1, unit_price: Money.new(12_900, "USD")),
31 LineItem.new(name: "USB-C Cable", quantity: 2, unit_price: Money.new(1_500, "USD"))
32 ],
33 shipping_address: Address.new(
34 line1: "1 Analytical Way",
35 city: "London",
36 postal_code: "EC1A 1BB",
37 country: "GB"
38 )
39 )
40 end
41end
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Mailer previews let you render real email templates in the browser without sending anything or hitting the database.
  2. 2Each public method maps to a preview URL, so one class documents every variant of a mailer.
  3. 3A private factory method keeps sample data in one place and lets each preview tweak just what it needs.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Previewing Rails mailers with sample data — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code