微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何测试 ActionMailer 对象中的实例变量?

如何解决如何测试 ActionMailer 对象中的实例变量?

我的 ActionMailer 对象中有一个 before_action 回调方法,负责设置一些实例变量。

class TestMailer < ApplicationMailer
   before_action :set_params

   def send_test_mail
     mail(to: @email,subject: subject)
   end

   def set_params
     @account = account.email 
     @date = some_action(account.updated_at)
   end
end

问题是如何在 rspec 测试中测试这些变量? 类似的东西:

describe TestMailer do 
 describe '#set_params' do
   described_class.with(account: account,subject: subject).send_test_mail.deliver_Now
   expect(@date).to eq(Date.today)
 end
end

任何线索将不胜感激。

解决方法

我认为与其测试实例变量,不如测试电子邮件正文,例如:

expect(mail.body.encoded).to include(account.updated_at)
,

您可以在模拟方法 spy 中设置一个 instance_variable_set,然后验证该间谍

class TestMailer < ApplicationMailer
 attr_accessor :day
 # ...
end

describe TestMailer do 
 let(:freeze_today) { Time.now.utc }

 it '#set_params' do 
  # freeze today
  allow_any_instance_of(TestMailer).to receive(:some_action)
  .with(account.updated_at)
  .and_return(freeze_today)

  # spy
  @spy = nil
  allow_any_instance_of(TestMailer).to receive(:day=) do |time|
   @spy = time
  end

  described_class.with(account: account,subject: subject)
  .send_test_mail
  .deliver_now

  expect(@spy).to eq(freeze_today)

  # or just simple like this  
  expect_any_instance_of(TestMailer).to receive(:day=).with(freeze_today)
 end
end

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。