Rails 5电子邮件拦截器rspec测试

时间:2019-05-14 14:47:27

标签: ruby-on-rails ruby ruby-on-rails-5

我正在努力防止意外发送给残疾用户的电子邮件。我认为最好的方法是注册邮件拦截器,并在此页面https://edgeapi.rubyonrails.org/classes/ActionMailer/Base.html

上插入delivering_email方法

这是我的初始化程序(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)

然后,我正在尝试将测试添加到我的应用中,以便确保用户可以注册开始,这就是该测试的样子:

  let(:from) { 'a@foo.com' }
  let(:to) { 'b@foo.com' }
  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

我得到一个错误:

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)>'

我在这里做错什么了吗?,我正在使用rails 5.1.0,不知道mailer api是否已更改或其他原因。

1 个答案:

答案 0 :(得分:1)

将主题更改为:

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

未使用模板。还有其他方法,这似乎可以解决此处描述的问题。