2017-12-10 31 views
-1

私は失敗事例について私のメーラーをテストしようとしています。たとえば、ユーザーが名前を入力しなかった場合などです。テストメーラー(Ruby on Rails)

これはこれは私のメーラーである私のテストコード

test "should not send email without name field" do 
    mail = ContactMailer.contact_email("", "[email protected]" , "07982900823", "Thank you for your email!") 

    assert_select mail.name do 
    assert_select "[value=?]", address.mail.name unless address.mail.name.blank? 
end 

です。

def contact_email(name, email, telephone, message) 
    @name = name 
    @email = email 
    @telephone = telephone 
    @message = message 

    mail cc: @email 
end 

これは私の検証ページ

<!DOCTYPE html> 
<html> 
<div> 
<head> 
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script> 
<script src="js/jquery.validate.js"></script> 
</head> 
</div> 
<div> 
<body> 
    <h1><u><%= t('contactpage.contactus') %></u></h1> 
    <p><%= t('contactpage.complete') %></p> 
    <%= form_tag request_contact_path, :id => 'contact_form', method: 'post' do %> 
    <br> 
    <%= label_tag :name, t('mailer.name') %> 
    <%= text_field_tag :name, '', title: "Enter Name", size: 20, :autofocus => true, :required => true%> 
    <br> 
    <%= label_tag :email, t('mailer.email') %> 
    <%= email_field_tag :email, '', title: "Enter Email", :autofocus => true, :required => true%> 
    <br> 
    <%= label_tag :telephone, t('mailer.telephone') %> 
    <%= telephone_field_tag :telephone, '', title: "Enter Telephone", :autofocus => true, :required => true%> 
    <br> 
    <%= label_tag :message, t('mailer.message') %> 
    <%= text_field_tag :message, '', title: "Enter Message", size: 100, :autofocus => true, :required => true%> 
    <br> 
    <%= submit_tag t('mailer.submit'), name: nil %> 
<% end %> 
</body> 
</div> 

<div> 
<script> 
$("contact_form").validate(); 
</script> 
</div> 
</html> 

私はアサーションのテストを編集できる方法上の任意の考えに感謝です! Railsのデフォルトの設定で

答えて

1

テスト環境で電子メールを送信する電子メールを提供し、コードを実行します(そうでない場合はすべきで文句を言わない、実際に電子メールを送信し、それはあなたのテストでそうActionMailer::Base.deliveries

に追加されます名前がない)、ActionMailer::Base.deliveriesのサイズが変更されているかどうかを確認します。

test "should not send email without name field" do 
    assert_no_difference 'ActionMailer::Base.deliveries.size' do 
    # run code that operates mailer, but without name 
    post request_contact_url, params: { 
     name: '', 
     email: '[email protected]', 
     telephone: '12345678', 
     message: 'test message' 
    } 
    end 
end 

名前の空の文字列を置くのは、ユーザーがフォームに空のままにしておいた場合だと思います。また、whitespece文字だけの文字列とnameパラメータを省略してテストすることもできます。

mailers section of the Rails Guide on testing