编写邮件导轨的测试

时间:2013-11-07 21:11:51

标签: ruby-on-rails ruby rspec

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

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

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) }
...

我不确定在这里断言会有什么聪明之处? 就像邮件应该发送或者不应该发送,如果我这样做反过来。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

动作邮件程序是一个糟糕的地方,可以执行任何逻辑,因为它有类似类的方法,在实例上无法访问的访问器等奇怪的混合,等等。编写一个可以检查是否发送的presenter类首先发送邮件并使用该演示者类在邮件程序中执行用户的任何特定表示。你可以测试演示者然后在邮件的概念之外,就像普通对象一样。

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?