RSpec truncates the mail program

I have a UserMailDispatcher class whose task is to forward mail through ActiveMailer based on certain criteria.

I am trying to test it using RSpec, but I do not understand. I would like to somehow drown out the test mail program and see if its class supplies correctly. Here is what I still have:

All my mailers inherit ApplicationMailer:

application_mailer.rb

 class ApplicationMailer < ActionMailer::Base append_view_path Rails.root.join('app', 'views', 'mailers') end 

user_mail_dispatcher_spec.rb

 require 'rails_helper' describe UserMailDispatcher do class UserMailer < ApplicationMailer def test_mail mail end end it "mails stuff" do ??? end end 

I want to check that the dispatcher can correctly deliver / send mail. However, I cannot name UserMailer.test_mail.deliver_now . I get the missing template 'user_mailer/test_mail' I tried adding type: :view to spec and use stub_template 'user_mailer/test_mail.html.erb' , but I get the same error.

I have a UserMailer parameter, but I don’t want to test any of its methods here, since they are more likely to change.

Any ideas on how best to deal with this?

+4
source share
3 answers

I ran into this problem when I tested with DummyMailer, and to get around this, I just asked the mail method to return plain text as follows:

 mail do |format| format.text { render plain: "Hello World!" } end 

Here is the documentation for it , scroll through the list a bit to find the section you need.

+1
source

Add the required template and test without ActionMailer::Base.deliveries around using ActionMailer::Base.deliveries . Here is an example (in minitest) from the manual ( http://guides.rubyonrails.org/testing.html#testing-your-mailers ).

 require 'test_helper' class UserMailerTest < ActionMailer::TestCase test "invite" do # Send the email, then test that it got queued email = UserMailer.create_invite(' me@example.com ', ' friend@example.com ', Time.now).deliver_now assert_not ActionMailer::Base.deliveries.empty? # Test the body of the sent email contains what we expect it to assert_equal [' me@example.com '], email.from assert_equal [' friend@example.com '], email.to assert_equal 'You have been invited by me@example.com ', email.subject assert_equal read_fixture('invite').join, email.body.to_s end end 
0
source

Here's how to verify that the mail program is being called with the correct arguments.

 it 'sends email' do delivery = double expect(delivery).to receive(:deliver_now).with(no_args) expect(UserMailer).to receive(:test_mail) .with('my_arguments') .and_return(delivery) UserMailDispatcher.my_function end 
0
source

All Articles