ActionMailer :: Base.deliveries在Rails 4中的RSpec模型测试中始终为空

时间:2013-08-21 16:01:32

标签: ruby-on-rails rspec actionmailer

我有以下失败的测试:

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

1 个答案:

答案 0 :(得分:2)

should_receiveand_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,我检查在我的模型上调用方法会导致发送电子邮件。