【问题标题】:How can I test with RSpec that Rails 3.2 ActionMailer is rendering the correct view template?如何使用 RSpec 测试 Rails 3.2 ActionMailer 是否呈现正确的视图模板?
【发布时间】:2014-01-04 08:46:00
【问题描述】:

我正在使用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

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

更新

MyMailer#notify_customer 可能有一些逻辑(例如,取决于客户的语言环境)在不同的情况下选择不同的模板。控制器在不同情况下渲染不同的视图模板或多或少是类似的问题。用RSpec你可以写

expect(response).to render_template "....." 

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

【问题讨论】:

  • 你为什么要测试它?视图路径由 mailer 方法的名称定义。这里几乎不会出错。
  • @DominikGoltermann 查看我上面的更新

标签: ruby-on-rails rspec actionmailer rspec-rails


【解决方案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

【讨论】:

    【解决方案2】:

    好的,我明白你现在想要达到的目标。

    您应该能够通过在邮件程序上为使用特定参数调用的 mail 方法设置预期来测试调用了哪个模板。

    在你的测试中试试这个:

    MyMailer.should_receive(:mail).with(hash_including(:template => 'expected_template'))
    

    【讨论】:

    • 不,我不想测试特定模板的内容。正如你所说,这是一个观点规范。请看我的更新。在某些情况下,action_x 基于某种逻辑呈现不同的视图模板。我想测试一下这个逻辑。
    • 我也希望能够测试这个(渲染哪个模板)。只是对此处给出的解决方案的快速说明:我认为这不适用于呈现的模板是 implicit 的情况(它默认呈现与动作名称匹配的模板)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-24
    • 2013-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多