2016-12-11 71 views
-1

我創建了一個電影評論網站,允許登錄的用戶添加,編輯和刪除電影以及爲每部電影留下評論。我還爲我的聯繫表單發送了一封「假電子郵件」(僅在控制檯上顯示)。測試郵件/聯繫人

這是我第一次使用Ruby,所以我不確定如何測試我的控制器和聯繫人的方法。任何形式的建議將不勝感激。

contacts_controller.rb:

class ContactsController < ApplicationController 
def new 
@contact = Contact.new 
end 

def create 
@contact = Contact.new(params[:contact]) 
@contact.request = request 

if @contact.deliver 
    flash.now[:notice] = 'Thank you for your message. We will contact you soon!' 
    else 
    flash.now[:error] = 'Cannot send message.' 
    render :new 

    end 
end 
end 

contact.rb:

class Contact < MailForm::Base 
    attribute :name,  :validate => true 
    attribute :email,  :validate => /\A([\w\.%\+\-]+)@([\w\-]+\. 
    attribute :message 
    attribute :nickname, :captcha => true 

# Declare the e-mail headers. It accepts anything the mail method 
# in ActionMailer accepts. 
def headers 
    { 
    :subject => "My Contact Form", 
    :to => "[email protected]", 
    :from => %("#{name}" <#{email}>) 
    } 
    end 
end 

路線:

contacts GET /contacts(.:format)  contacts#new  
      POST /contacts(.:format)  contacts#create 
new_contact GET /contacts/new(.:format) contacts#new 

我測試至今:

require 'test_helper' 

class ContactsControllerTest < ActionController::TestCase 
include Devise::Test::ControllerHelpers 

test "should get contact" do 
get :new 
assert_response :success 

end 
end 

回答

0

你可以閱讀更多的信息在這裏http://edgeguides.rubyonrails.org/testing.html#testing-your-mailers

require 'test_helper' 

class ContactsControllerTest < ActionDispatch::IntegrationTest 
    test "ActionMailer is increased by 1" do 
    assert_difference 'ActionMailer::Base.deliveries.size', +1 do 
     post contacts_url, params: { name: 'jack bites', email: '[email protected]', message: 'sending message', nickname: 'jackbites' } 
    end 
    end 

    test "Email is sent to correct address" do 
    post contacts_url, params: { name: 'jack bites', email: '[email protected]', message: 'sending message', nickname: 'jackbites' } 
    invite_email = ActionMailer::Base.deliveries.last 
    assert_equal '[email protected]', invite_email.to[0] 
    end 
end 
+0

感謝您分享的鏈接。使用該鏈接,我一直在嘗試理解,但我仍不確定如何將這些原則應用於我的測試。 – sar

+0

查看'10.3功能測試'以在您的控制器中進行測試。如果你有問題,請告訴我。 – JackBites

+0

基於10.3我已經想出了以下測試: test「send email」do assert_difference'ActionMailer :: Base.deliveries.size',+1 do post send_email_url,params:{email:'info @ mymovies .COM」} 結束 SEND_EMAIL =的ActionMailer :: Base.deliveries.last 結束 能否請你指導我,如果我在正確的軌道上這裏我心亂如麻。 – sar

相關問題