1

我有以下失败的测试:

describe Image do
  describe 'a_method' do
    it 'sends email' do
      Image.count.should == 1
      expect do
        ImageMailer.deleted_image(Image.last.id).deliver
      end.to change(ActionMailer::Base.deliveries, :length)
    end
  end
end

这是我的邮件:

class ImageMailer < ActionMailer::Base
  layout 'email'
  default from: 'whee@example.com'

  def deleted_image image_id, recipient='whee@example.com'
    @image = Image.find(image_id)
    subject = "Image email"
    mail(to: recipient, subject: subject) do |format|
      format.text
      format.html { render layout: 'email' }
    end
  end
end

我的测试失败了Failure/Error: expect do length should have changed, but is still 0。我对我的邮件本身进行了另一个测试,它通过了:

describe ImageMailer do
  it 'should deliver the mail' do
    expect do
      subject.deliver
    end.to change { ActionMailer::Base.deliveries.length }.by(1)
  end
end

我不知道为什么ActionMailer::Base.deliveries在我的模型规范中总是为空,但在我的邮件规范中却不是。邮件显然有效。我的模型测试本来是不同的,测试我模型上的一个方法是否导致发送电子邮件,但是当它无法生成邮件传递时,我明确地尝试了该ImageMailer.deleted_image(Image.last.id).deliver行并且它不起作用。描述的对象是邮件程序类的 RSpec 测试有什么特别之处吗?

以下是我的 config/environments/test.rb 文件中的一些相关行:

config.action_mailer.delivery_method = :test
config.action_mailer.default_url_options = {host: 'localhost:3000'}
config.action_mailer.perform_deliveries = true
4

1 回答 1

2

should_receivewith的组合使and_return我的测试通过:

it 'send email for an image not in Amazon that is in our table' do
  mailer = double
  mailer.should_receive(:deliver)
  ImageMailer.should_receive(:deleted_image).and_return(mailer)
  ImageMailer.deleted_image(Image.last.id).deliver
end

当我注释掉时ImageMailer.deleted_image(Image.last.id).deliver,测试按预期失败。由此,我能够替换ImageMailer.deleted_image(Image.last.id).deliver为我的实际测试,在该测试中我检查在我的模型上调用方法是否会导致发送电子邮件。

于 2013-08-21T16:18:56.617 回答