【问题标题】:ActionMailer: undefined method `recipients' forActionMailer:未定义的方法“收件人”
【发布时间】:2019-10-06 17:33:29
【问题描述】:

我正在 Rails 3.2 上为我的一个 ActionMailer - InvitationMailer 编写测试,但是,它似乎没有找到“收件人”方法。

我的测试如下所示:

  describe "Invitation" do
    it "should send invitation email to user" do
    user = Factory :user

    email = InvitationMailer.invitation_email(user).deliver
    # Send the email, then test that it got queued
    assert !ActionMailer::Base.deliveries.empty?

    # Test the body of the sent email contains what we expect it to
    assert_equal [user.email], email.to
    assert_equal "You have been Invited!", email.subject

    end

我的 InvitationMailer 如下所示:

class InvitationMailer < ActionMailer::Base
  default from: "webmaster@myapp.com"

  def invitation_email(user)
    recipients  user.email
    from        "invitations@myapp.com"
    subject     "You have been Invited!"
    body        :user => user
  end

end

但是,我收到以下错误消息:

 Failure/Error: email = InvitationEmail.invitation_email(user).deliver
 NoMethodError:
   undefined method `recipients' for #<InvitationMailer:0x007fca0b41f7f8>

知道它可能是什么吗?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 actionmailer


    【解决方案1】:

    这是来自Rails Guide for ActionMailer 的示例:

    class UserMailer < ActionMailer::Base
      default :from => "notifications@example.com"
    
      def welcome_email(user)
        @user = user
        @url  = "http://example.com/login"
        mail(:to => user.email,
             :subject => "Welcome to My Awesome Site",
             :template_path => 'notifications',
             :template_name => 'another')
      end
    end
    

    让你的代码看起来更像这样可能更容易解决,所以我首先将它重写为如下所示:

    class InvitationMailer < ActionMailer::Base
      default from: "webmaster@myapp.com"
    
      def hassle_email(user)
        @user = user
        mail(:to => user.email,
             :subject => "You have been Invited!")
      end
    end
    

    然后您将拥有:to:subject@user 对象传递给邮件程序“视图”,这与任何其他视图一样。

    既然您使用的是recipients,我不确定您是否尝试将电子邮件发送到多个电子邮件地址。如果是这样,根据 ActionMailer 文档:

    可以在一封电子邮件中向一个或多个收件人发送电子邮件 (例如,通知所有管理员新注册)通过设置列表 发送到 :to 键的电子邮件。电子邮件列表可以是电子邮件数组 地址或单个字符串,地址用逗号分隔。

    【讨论】:

    • 语法似乎有点不同。显然,收件人、发件人等是方法调用——从你的回答来看,尚未使用。相反,您正在使用邮件方法调用。有什么区别? (参考railscasts.com/episodes/61-sending-email
    • @Newton 虽然 railscasts 通常是很棒的资源,但如果它们太旧,您需要小心使用它们。你提到的那个几乎是5年前的。一般来说,如果您有任何问题,请务必查看最新的 rails 文档。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-17
    • 1970-01-01
    • 2014-03-18
    • 1970-01-01
    相关资源
    最近更新 更多