【问题标题】:RSpec stubbing a mailerRSpec 存根邮件程序
【发布时间】:2015-10-23 11:56:28
【问题描述】:

我有一个UserMailDispatcher 班级,其工作是根据某些标准通过ActiveMailer 挖掘邮件。

我正在尝试使用 RSpec 对其进行测试,但效果不佳。我想以某种方式存根一个测试邮件并查看该类是否正确交付它。到目前为止,这是我所拥有的:

我所有的邮件程序都继承自 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

我想测试调度程序是否可以正确排队/传递邮件。但是,我似乎无法致电UserMailer.test_mail.deliver_now。我得到missing template 'user_mailer/test_mail' 我尝试将type: :view 添加到规范并使用stub_template 'user_mailer/test_mail.html.erb',但我得到了同样的错误。

我确实定义了UserMailer,但我不想在这里测试它的任何方法,因为这些方法更有可能发生变化。

关于如何最好地处理这个问题的任何想法?

【问题讨论】:

  • 您是否有特定的原因要存根,或者您只是想知道邮件已发送?另外,是否有某些原因您无法实现所需的模板?邮件操作通常有一个关联的模板。
  • 我只是想知道所有必需的邮件都已发送。我喜欢只实现测试模板的想法,它可以工作(谢谢!!),但这似乎是一个非常老套的解决方案。我觉得更好的方法是以某种方式存根模板。
  • 你会在生产中使用test_mail 操作吗?

标签: ruby-on-rails ruby rspec actionmailer


【解决方案1】:

使用ActionMailer::Base.deliveries 添加所需的模板并在没有存根的情况下进行测试。这是指南 (http://guides.rubyonrails.org/testing.html#testing-your-mailers) 中的一个示例(在 minitest 中)。

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

【讨论】:

  • 我知道你在这里做什么,但我想做的是将 UserMailDispatcher 与任何实际的 UserMailer 方法分离。我不想调用一个实际的方法并渲染一个实际的模板(我可以在 UserMailer 测试中做实际的模板规范),我只想存根它们。
【解决方案2】:

以下是如何测试使用正确参数调用邮件程序的方法。

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

【讨论】:

    【解决方案3】:

    我在使用 DummyMailer 进行测试时也遇到了这个问题,为了解决这个问题,我只是要求邮件方法返回如下纯文本:

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

    这里是documentation for it,向下滚动一点找到正确的部分。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-17
      • 1970-01-01
      • 2012-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多