2012-05-07 17 views
1

我正在爲我的一個ActionMailers - InvitationMailer寫一個測試,但是,它似乎找不到「收件人」方法。ActionMailer:未定義的方法`收件人'爲

我的測試如下所示:

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: "[email protected]" 

    def invitation_email(user) 
    recipients user.email 
    from  "[email protected]" 
    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> 

任何想法它可能是?

+0

什麼版本的Rails?猜測2.X? – x1a4

+0

不,其軌道3.2.2 – Karan

回答

3

下面是來自Rails Guide for ActionMailer一個例子:

class UserMailer < ActionMailer::Base 
    default :from => "[email protected]" 

    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: "[email protected]" 

    def hassle_email(user) 
    @user = user 
    mail(:to => user.email, 
     :subject => "You have been Invited!") 
    end 
end 

然後,您將:to,:subject@user對象傳遞給郵件視圖,就像任何其他視圖一樣。

您是否使用recipients我不確定您是否嘗試將電子郵件發送到多個電子郵件地址。如果是這樣,根據的ActionMailer文檔:

它可以發送電子郵件給一個或多個收件人在一封電子郵件 (用於如通知新註冊的所有管理員)通過設置 電子郵件到列表:關鍵。電子郵件列表可以是電子郵件地址的一個陣列,也可以是地址或單個字符串,地址之間用逗號分隔。

+0

語法看起來有點不同。顯然,收件人,從等等是方法調用 - 從您的答案中,沒有被使用。而是使用郵件方法調用。有什麼不同? (參考http://railscasts.com/episodes/61-sending-email) – Karan

+2

@Newton雖然railscasts通常是很棒的資源,但如果它們太舊,則需要小心使用它們。你提到的那個幾乎是在5年前。一般來說,如果您有任何問題,請務必查看最新的rails文檔。 –

+0

謝謝@Kevin Bedell – Karan

相關問題