鉴于我的RewardMailer
有以下预览:
class RewardMailerPreview < ActionMailer::Preview
@mailman = 'mailman@mailman.ninja'
@alice = User.create(email: 'ali@example.com')
@bob = User.create(email: 'ali@example.com')
@subject = 'I Vooshed my website'
@btc_address = '1BitcoinKKKKKKKK'
@amount = 0.004
# Preview this email at http://localhost:3000/rails/mailers/reward_mailer/invoice_due
def invoice_due
RewardMailer.invoice_due(
alice: @alice,
subject: @subject,
btc_address: @btc_address
)
end
end
我收到以下错误:
NoMethodError in Rails::MailersController#preview
undefined method `email' for nil:NilClass
Extracted source (around line #13):
11 @alice = invoice_info[:alice]
12 @subject = invoice_info[:subject]
13 mail to: @alice.email, subject: @subject
14 end
我的RewardMailer
有行动:
def invoice_due(invoice_info)
@btc_address = invoice_info[:btc_address]
@alice = invoice_info[:alice]
@subject = invoice_info[:subject]
mail to: @alice.email, subject: @subject
end
并测试:
test 'invoice_due' do
mail = RewardMailer.invoice_due(
alice: alice,
subject: subject,
btc_address: btc_address
)
assert_equal subject, mail.subject
assert_equal [alice.email], mail.to
assert_equal [mailman], mail.from
assert_match btc_address, mail.body.encoded
end
答案 0 :(得分:3)
您在类级别设置@alice
,但是您尝试从实例中读取它。我想你这样做是为了在不同的电子邮件中共享变量初始化代码?你可以这样做:
class RewardMailerPreview < ActionMailer::Preview
def set_defaults
@mailman = 'mailman@mailman.ninja'
@alice = User.create(email: 'ali@example.com')
@bob = User.create(email: 'ali@example.com')
@subject = 'I Vooshed my website'
@btc_address = '1BitcoinKKKKKKKK'
@amount = 0.004
end
def invoice_due
set_defaults
RewardMailer.invoice_due(
alice: @alice,
subject: @subject,
btc_address: @btc_address
)
end
end