简体   繁体   English

Rails Mailer 上的 RSpec class_spy

[英]RSpec class_spy on Rails Mailer

I am trying to test that a specific mailer class is used when a model is saved.我正在尝试测试在保存模型时是否使用了特定的邮件程序类。 In my model I have:在我的模型中,我有:

class Foo < ActiveRecord::Base
  def send_email
    if some_condition
      FooMailer.welcome.deliver_now
    else
      FooBarMailer.welcome.deliver_now
    end
  end
def

In my tests for Foo class I have the following在我对 Foo 类的测试中,我有以下内容

it 'uses the foo bar mailer' do
  foo_mailer = class_spy(FooMailer)
  subject.send_email
  # some_condition will evaluate to false here, so we'll use the FooMailer
  expect(foo_mailer).to have_received :welcome
end

When I run this test it fails with:当我运行这个测试时,它失败了:

(ClassDouble(FooMailer) (anonymous)).welcome(*(any args))
       expected: 1 time with any arguments
       received: 0 times with any arguments

The issue would seem to be that you haven't swapped out the current definition of your mailer class with the spy, so your spy isn't receiving any messages. 问题似乎是您没有与间谍交换出邮件类的当前定义,因此您的间谍没有收到任何消息。 To replace it, you would use the stub_const method: 要替换它,可以使用stub_const方法:

it 'uses the foo bar mailer' do
  foobar_mailer = class_spy(FooBarMailer)
  stub_const('FooBarMailer', foobar_mailer)
  subject.send_email
  # some_condition will evaluate to false here, so we'll use the FooBarMailer
  expect(foobar_mailer).to have_received :welcome
end
foo_mailer = class_spy(FooMailer).as_stubbed_const

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM