2

我正在尝试测试只应将邮件发送给经过验证的用户的邮件发送方法。

所以我的邮件中有一个这样的方法:

def send_hints(user)
    @user = user
    mail :to => user.email, :subject => "Your hints for the day"
end

我正在努力确保只有经过验证的用户才能收到此信息。所以 user.verified_at 不是 null/nil。

现在开始写测试:

describe "Emails should be sent only to verified user"
  let(:user) { FactoryGirl.create(:user, :verified_at => DateTime.now) }
  let(:mail) { UserMailer.send_hints(user) }
...

我不确定在这里断言什么是明智的?如果我以相反的方式发送邮件,则应该发送或不发送邮件。

4

2 回答 2

1

这是测试它的一种方法:

# config/environments/test.rb
YourApplication::Application.configure do
  config.action_mailer.delivery_method = :test
end


# spec/your_spec.rb
describe 'Emails should be sent only to verified user' do
  let(:user) { FactoryGirl.create(:user, verified_at: verified_at) }
  before { UserMailer.send_hints(user) }
  subject { ActionMailer::Base.deliveries.last.to }
  context 'When the user is verified' do
    let(:verified_at) { DateTime.now }
    it { should include(user.email) }
    end
  end

  context 'When the user is not verified' do
    let(:verified_at) { nil }
    it { should_not include(user.email) }
  end
end
于 2013-11-07T21:31:08.143 回答
0

action mailer 是一个执行任何逻辑的糟糕地方,因为它具有类的奇怪组合,例如方法、实例上不可访问的访问器等。编写一个演示者类,可以检查是否在首先并使用该演示者类在邮件程序中执行用户的任何特定表示。您可以在邮件程序的概念之外测试演示者,就像您测试普通对象一样。

class HintMailerPresenter
  def initialize(user)
    @user = user
  end

  def verified?
    user.whatever and whatever
  end
end

# in you controller/mail sending location

@presenter = HintMailPresenter.new(user)
Mailer.send_hints(@presenter).deliver if @presenter.verified?
于 2013-11-08T01:56:20.077 回答