2017-07-20 3 views
0

レールのメーラーでは、すべてのメソッドがクラスメソッドになることはわかっています。 しかし、私はと呼ばれる自分のメーラーメソッドをテストすることはできません。rspecのレールで呼び出されるメーラーの動作をテストできません

user_mailer_spec.rb:

it "should call send_notifition method" do 
     @user = FactoryGirl.build(:user) 
     notify_email = double(:send_notifition) 
     expect(UsersMailer.new).to receive(:notify_email).with(@user) 
     @user.save 
end 

user_mailer.rb:

def notify(user) 
    mail to: user.email, subject: "Example" 
end 

user.rb:

after_commit :send_notifition 

private 

def send_notifition 
    UsersMailer.notify(self) 
end 

上記のコードは合格しませんが、私がself.notifitionへの通知を変更すると、それは次のようになります:

def self.notify(user) 
    mail to: user.email, subject: "Example" 
end 

答えて

1

まず、メールをテストするための素晴らしい宝石をご紹介したいと思います。https://github.com/email-spec/email-spec

Userモデルでインスタンス化されたものとは別のインスタンスにモックを入れて、UsersMailer.newにアサーションしているという問題があると思います。私は一般的に何の問題もなく、このようなメールをテストします。私は代わりにexpect(UsersMailer.new)expect(UsersMailer)をやっても、私は電子メールが実際に配信されていることを主張してるということではない取るよどのように

it "should call send_notifition method" do 
    @user = FactoryGirl.build(:user) 

    mail = double(:mail) 
    expect(UsersMailer).to receive(:notify_email).with(@user).and_return(mail) 
    expect(mail).to receive(:deliver_later) # or deliver_now, if you don't use a background queue 

    @user.save 
end 

注意を(私は、ステートメントが欠落している届けると思いますあなたのコードで)。

希望に役立ちます。

+0

申し訳ありませんが、間違い。私は「expect(UsersMailer).to(:notify_email).with(@user)」を受け取りますが、動作しなくなるまでです。 – Hung

+0

私はあなたの提案を試みたが、合格しないまでです。 – Hung

+0

私が言及したようにコールを修正しましたか?私。コールバックは 'UsersMailer.notify(self) 'でなければなりません。deliver_now'(または、バックグラウンドワーカーを使用する場合は 'deliver_later'、古いRailsバージョンを使用している場合は' deliver'のみ)を使用します。 –

0

解決: @Clemens Koflerに感謝します。

  • まず:user.rbファイルの宝石 "email_spec" をインストールし、変更する必要はありません

から

after_commit :send_notifition 

private 

def send_notifition 
    UsersMailer.notify(self) 
end 

へ 私は私のコードで多くの間違いを持っ​​ています
after_commit :send_notifition 

private 

def send_notifition 
    UsersMailer.notify(self).deliver 
end 
  • 第二:変更user_mailer_spec.rbファイル最後に

    it "should call send_notifition_mail_if_created_new_hospital method" do 
         @user = FactoryGirl.build(:user) 
         # I don't know why "expect(@user).to receive(:send_notifition)" not passed here 
         mail = double(:mail) 
         expect(UsersMailer).to receive(:notify_email).with(@user).and_return(mail) 
         allow(mail).to receive(:deliver) 
         @user.save 
        end 
    
    • it "should call send_notifition method" do 
           @user = FactoryGirl.build(:user) 
           expect(@user).to receive(:send_notifition) 
           notify_email = double(:send_notifition) 
           expect(UsersMailer.new).to receive(:notify_email).with(@user) 
           @user.save 
          end 
      

      から

    :メーラーを使用することができるテスト環境用のconfig /環境/ test.rbのconfigメーラ(仕様がテスト環境で実行されているため)

関連する問題