【问题标题】:Get an instance variable from Mailer in Rspec从 Rspec 中的 Mailer 获取实例变量
【发布时间】:2014-08-11 08:34:21
【问题描述】:

我正在尝试验证在调用我的 UserMailer 模型中的方法时是否设置了给定的实例变量。我正在使用 RSpec,但似乎无法弄清楚。

这是邮件:

class UserMailer < ActionMailer::Base
  def client_connexion_notification(connexion)
    @connexion = connexion
    mail to: "test@test.com", subject: "Connexion!"
  end
end

还有测试:

it "should set @connexion" do
  UserMailer.client_connexion_notification("stackoverflow")
  UserMailer.instance_variable_get(:@connexion).should == "stackoverflow"
end

我知道我应该在模型的一个实例上调用 instance_variable_get,但我猜 ActionMailer 的行为有所不同,因为您实际上不应该创建它的新实例。 (方法 new 是私有的)

我能想到的替代方法之一是测试使用 ActionMailer::Base.deliveries 创建的实际电子邮件的内容,但我更愿意测试变量的实际内容。

顺便说一句,我认为我可以使用 ActionMailer::Base.deliveries.last.instance_variable_get(:@connexion) 来获取它,但是不行。

【问题讨论】:

    标签: ruby-on-rails ruby rspec actionmailer


    【解决方案1】:

    您可以改为测试结果电子邮件中是否存在变量,如下所示:

    it "should set @connexion" do
      mail = UserMailer.client_connexion_notification("stackoverflow")
      mail.raw_source.should include("stackoverflow")
    end
    

    这假设邮件不是多部分的。

    【讨论】:

    • 是的,我已经想到了(正如我在问题的内容中所说),但这对于我想要测试的东西来说并不理想。就没有别的办法了吗?
    • 对不起,我错过了你帖子的那一部分。正如您自己所说,问题在于您没有创建 ActionMailer 的实例。我想不出任何直接测试@connexion 值的好方法。为什么检查邮件输出不是一个好选择?
    • 我只是在这里简化了它,但是在我正在处理的这个项目中,根据 3 个变量,我的邮件输出可以有 9 种不同的内容——这会使测试更加复杂。只测试这三个变量会更容易,但我想我别无选择。感谢您的帮助!
    猜你喜欢
    • 2017-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-08
    • 1970-01-01
    • 1970-01-01
    • 2012-09-20
    相关资源
    最近更新 更多