Remember_me
Remember_me

Reputation: 283

Rails 5 email interceptor rspec test

I am trying to prevent accidental emails to disabled users. And I figured the best way to do it would be to register mail interceptor, and hook into delivering_email method per this page https://edgeapi.rubyonrails.org/classes/ActionMailer/Base.html

This is the code of my initializer (config/initializers/email_interceptor.rb) :

class EmailInterceptor
  def self.delivering_email(message)
    if User.where('email = ? AND disabled_at is not null', message.to).exists?
      message.perform_deliveries = false
    end
  end
end

ActionMailer::Base.register_interceptor(EmailInterceptor)

Then I'm trying to add tests to my app so I can make sure that users can register to begin with, and this is how that test looks like :

  let(:from) { '[email protected]' }
  let(:to) { '[email protected]' }
  subject { ActionMailer::Base.mail(to: to, from: from).deliver }

  it 'sends emails to non existing users' do
    expect { subject }.to change(ActionMailer::Base.deliveries, :count)
  end

There is an error that I get :

Failure/Error: subject { ActionMailer::Base.mail(to: to, from: from).deliver }

     ActionView::MissingTemplate:
       Missing template action_mailer/base/mail with "mailer". Searched in:
         * "action_mailer/base"
     # ./spec/mailers/email_interceptor_spec.rb:6:in `block (2 levels) in <top (required)>'

Am I doing something wrong here? I am using rails 5.1.0 and I wonder if mailer api has changed or something.

Upvotes: 3

Views: 837

Answers (1)

ant
ant

Reputation: 22948

Change your subject to :

subject do 
  ActionMailer::Base.mail(to: to, from: from, subject: 'test', body: 'test').deliver
end

No template used. There are other ways too, this seems to work for the problem what is described here.

Upvotes: 4

Related Questions