2017-03-29 3 views
0

응용 프로그램에서 메일러를 테스트하여 원하는 작업을 수행하고 있는지 확인하고 싶습니다.레일 5 - 응용 프로그램 메일러 테스트

class LessonMailer < ApplicationMailer 
    def send_mail(lesson) 
     @lesson = lesson 
     mail(to: lesson.student.email, 
     subject: 'A lesson has been recorded by your tutor') 
    end 
end 

이는 사양/우편물 디렉토리 나는 'send_mail'방법은 내가 그러나, 나는이 오류를 얻고 원하는대로 작동하는지 테스트 할

require "rails_helper" 

RSpec.describe LessonMailer, :type => :mailer do 
    describe "lesson" do 

    let(:student){ FactoryGirl.create :user, role: 'student', givenname: 'name', sn: 'sname', email: '[email protected]' } 
    let(:lesson ){ FactoryGirl.create :lesson, student_id: 2 } 
    let(:mail ){ LessonMailer.send_mail(lesson).deliver_now 

    it "renders the headers" do 
     expect(mail.subject).to eq("A lesson has been recorded") 
     expect(mail.to).to eq(["[email protected]"]) 
     expect(mail.from).to eq(["[email protected]"]) 
    end 

    it "renders the body" do 
    expect(mail.body.encoded).to match("A lesson form has been recorded") 
    end 
    end 
end 

내 테스트입니다. 이 문제를 해결하려면 어떻게해야합니까? 고맙습니다.

NoMethodError: 
    undefined method `email' for nil:NilClass 
# ./app/mailers/lesson_mailer.rb:4:in `send_mail' 

답변

1

따라서 FactoryGirl을 사용하면 필요한 다른 객체를 인스턴스화하면됩니다. 코드를 읽으면 lessonstudent이고 학생은 email입니다. 따라서 필요한 모든 것을 작성한 다음 방법을 호출하십시오. 당신은 test 환경이 당신이 이메일이 ActionMailer :: Base.deliveries 배열에 전달 될 것인지 알려해야합니다

# Here's the student factory (for this use case, you'll probably want to make it more general) 
FactoryGirl.define do 
    factory :user do 
    role 'student' 
    givenname 'name' 
    sn 'sname' 
    email '[email protected]' 
    end 
end 

# Here's your test 
require "rails_helper" 

RSpec.describe LessonMailer, :type => :mailer do 
    describe "lesson" do 
    let(:student){ create :student, email: '[email protected]' } 
    let(:lesson ){ create :lesson, student: student } 
    let(:mail ){ LessonMailer.send_mail(lesson) } 

    it ' ... ' do 
     ... 
    end 
    end 
end 

: 당신이 뭔가를 할 수 있습니다. 이렇게하려면, .deliver_now

config.action_mailer.delivery_method = :test 

config/environments/test.rb

마지막으로 한가지에 설정되어 있는지 확인, 당신이 그것을 필요합니다 있는지 확실하지 않습니다 만들지 만, 당신과 함께 메일러를 호출해야 할 수도 있습니다 . 이처럼

:

let(:mail){ LessonMailer.send_mail(lesson).deliver_now } 

...하거나 보낼 수 없습니다. 나는 정상을 기억할 수 없다.

어떻게 진행되는지 알려주세요.

+0

답장을 보내 주셔서 감사합니다. 그러나 솔루션을 구현할 때 오류가 발생합니다. NoMethodError : 정의되지 않은 메소드 'email'for nil : NilClass # ./app/mailers/lesson_mailer.rb:4:in'send_mail ' 이 문제를 해결하려면 어떻게해야합니까? –

+0

공장을 구현 했습니까? 'email' 속성을 가진'student' 공장이 있습니까? 'NilClass' 에러는 흥미 롭습니다. 왜냐하면'.email'을 호출하려고하는'student'가 없다는 것을 의미하기 때문입니다. 그래서 우리는 학생이 인스턴스화되고 있는지, 그리고 그것이'email' 속성을 가지고 있는지 확인해야합니다. 다음은 공장을 만드는 데 필요한 참고 자료입니다. https://github.com/brennovich/cheat-ruby-sheets/blob/master/factory_girl.md –

+0

도움을 주셔서 감사합니다. 나는 그것을 마침내 해결할 수있었습니다. student_id로 수업을하기 위해 공장을 설정하는 방법이 문제였습니다. –