2012-02-10 3 views
0

Я переношу приложение Rails 2.3.14 в Rails 3.0. В нем почтовая программа отправляет сообщение с вложением. Используя приведенный ниже код, это работало без проблем в версии 2.3.x.Не удается получить Rails 3 ActionMailer для приема вложения

def notification(material, recipient, path_to_file) 
    enctype = "base64" 

    @recipients = recipient.email 
    @from  = material.person.email 
    @reply_to = material.person.email 
    @subject  = "New or updated materials: " + material.name 
    @sent_on  = Time.now 
    @content_type = "multipart/mixed" 
    @headers['sender'] = material.person.email 

    part :content_type => "text/plain", 
      :body => render_message('notification', 
      :material => material, 
      :url => material.full_url_to_material) 

    attachment :content_type => "application" + "/" + material.file_type, 
       :body => File.read(path_to_file), 
       :filename => File.basename(material.file), 
       :transfer_encoding => enctype, 
       :charset => "utf-8" if !!material.send_as_attachment 

end 

Чтение через Rails 3.0 ActionMailer instructions, я модифицировал метод следующим образом:

def notification(material, recipient, path_to_file) 
    @material = material 
    @url = material.full_url_to_material 
    attachments[material.file_file_name] = File.open(path_to_file, 'rb'){|f| f.read} if material.send_as_attachment? 
    headers['sender'] = material.person.email 
    mail(:to => recipient.email, 
     :subject => "New or updated materials: " + material.name, 
     :reply_to => material.person.email, 
     :from => material.person.email) 
    end 

MaterialMailer # уведомление вызывается при создании материала. У меня есть следующая спецификация, чтобы проверить это:

it "will include the materials as an attachement with the the send_as_attachment field is set to 1" do 
    it = Material.create(@materials_hash.merge(:send_notification => "1", :send_as_attachment => "1")) 
    email = ActionMailer::Base.deliveries[0] 
    email.body.should =~ Regexp.new("Name of the posted material: " + it.name) 
    email.has_attachments?.should be_true 
    end 

Как я уже говорил, это отлично работало в 2.3. Теперь, если я установил send_as_attachment флаг один, я получаю следующее сообщение об ошибке, ссылаясь на email.body.should строку:

1) Material will include the materials as an attachement with the the send_as_attachment field is set to 1 
    Failure/Error: email.body.should =~ Regexp.new("Name of the posted material: " + it.name) 
     expected: /Name of the posted material: My material/ 
      got: (using =~) 
     Diff: 
     @@ -1,2 +1 @@ 
     -/Name of the posted material: My material/ 

Если изменить спецификацию и установить send_as_attachment 0, я получаю следующее сообщение об ошибке , ссылаясь на has_attachments? линия:

1) Материал будет включать в себя материалы в качестве прикрепленного с send_as_attachment в поле установлено значение 1 Failure/Ошибка: email.has_attachments .Should be_true ожидается ложным, чтобы быть правдой

Так включая приложение как-то нарушает электронную почту.

Я пробовал другие методы для крепления материала:

attachments[material.file_file_name] = {:mime_type => "application" + "/" + material.file_content_type, 
       :content => File.read(material.file.path), 
       :charset => "utf-8"} 

Я попытался жестко прописывать файловые пути к известным файлам. Но не повезло.

Где бы я ни смотрел?

+1

Ирония иронии, после окончания этого опуса, я только что понял. Мне нужно взглянуть на первую часть письма для тела. – TDH

+0

mail.parts [0] .body.should = ~ Regexp.new («Название опубликованного материала:« + it.name ») – TDH

+1

Вы должны написать свой ответ о том, как вы его получили, так что другие люди, которые сталкиваются с этим, могут найти Это :} –

ответ

0

предложение Per Кристофера, вот почтовая программа и спецификации код, который я использовал, чтобы заставить его работать:

def notification(material, recipient, path_to_file) 
    @material = material 
    @url = material.full_url_to_material 
    attachments[material.file_file_name] = File.open(material.file.path, 'rb'){|f| f.read} if material.send_as_attachment? 
    headers['sender'] = material.person.email 
    mail(:to => recipient.email, 
     :subject => message_subject("New or updated materials: " + material.name), 
     :reply_to => material.person.email, 
     :from => material.person.email) 
    end 

    it "will include the materials as an attachment with the the send_as_attachment field is set to 1" do 
    it = Material.create(@materials_hash.merge(:send_notification => "1", :send_as_attachment => "1")) 
    Delayed::Worker.new(:quiet => true).work_off 
    email = ActionMailer::Base.deliveries[0] 
    email.parts.each.select{ |email| email.body =~ Regexp.new("Name of the posted material: " + it.name)}.should_not be_empty 
    email.has_attachments?.should be_true 
    end 

В спецификации, я должен был проверить тело каждого из частей письма, поскольку это не было последовательным в отношении того, является ли вложение первой или второй частью.

Смежные вопросы