如何使用 RSpec 测试 Rails 3.2 ActionMailer 正在渲染正确的视图模板?

p.m*_*los 5 rspec ruby-on-rails actionmailer rspec-rails

我正在使用rspec-rails,我想测试我的邮件程序是否正在渲染正确的视图模板。

describe MyMailer do
  describe '#notify_customer' do
    it 'sends a notification' do
      # fire
      email = MyMailer.notify_customer.deliver

      expect(ActionMailer::Base.deliveries).not_to be_empty
      expect(email.from).to include "cs@mycompany.com"

      # I would like to test here something like
      # ***** HOW ? *****
      expect(template_path).to eq("mailers/my_mailer/notify_customer")
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

这是一个有效的方法吗?或者我应该做一些完全不同的事情?

更新

MyMailer#notify_customer可能有一些逻辑(例如,根据客户的区域设置)在不同情况下选择不同的模板。这或多或少与控制器在不同情况下渲染不同视图模板的问题类似。有了RSpec你就可以写

expect(response).to render_template "....." 
Run Code Online (Sandbox Code Playgroud)

它有效。我正在为邮寄者寻找类似的东西。

lul*_*ala 1

我认为这离上面的答案更近了一步,因为它确实测试了隐式模板。

    # IMPORTANT!
    # must copy https://gitlab.com/gitlab-org/gitlab/-/blob/master/spec/support/helpers/next_instance_of.rb
    it 'renders foo_mail' do
      allow_next_instance_of(described_class) do |mailer|
        allow(mailer).to receive(:render_to_body).and_wrap_original do |m, options|
          expect(options[:template]).to eq('foo_mail')

          m.call(options)
        end
      end

      body = subject.body.encoded
    end
Run Code Online (Sandbox Code Playgroud)