0

我尝试使用这个How do I test Pony emailing in a Sinatra app, using rspec? 测试发送电子邮件的 Rails 3.1 应用程序。发送工作正常,但我很难让测试正常工作。这是我到目前为止所拥有的...

规范/spec_helper.rb

config.before(:each) do
    do_not_send_email
end
.
.
.
def do_not_send_email
    Pony.stub!(:deliver) # Hijack to not send email.
end

在我的 users_controller_spec.rb

it "should send a greeting email" do
    post :create, :user => @attr
    Pony.should_receive(:mail) do |params|
        params[:to].should == "nuser@gmail.com"
        params[:body].should include("Congratulations")
    end
end

我明白了...

失败:

1) UsersController POST 'create' 成功应该发送一封问候邮件失败/错误:Pony.should_receive(:mail) do |params| (Pony).mail(any args) expected: 1 time received: 0 times # ./spec/controllers/users_controller_spec.rb:121:in `block (4 levels) in '

看起来 Pony 没有收到电子邮件,但我知道真正的电子邮件正在发送出去。

有任何想法吗?

4

2 回答 2

2

这是我最终完成的测试...

it "should send a greeting email" do
    Pony.should_receive(:deliver) do |mail|
        mail.to.should == [ 'nuser@gmail.com' ]
        mail.body.should =~ /congratulations/i
    end
    post :create, :user => @attr
end

Pony.should_rececieve 需要 :deliver (不是 :mail),do/end 做了一点改动,post 是在设置后完成的。

希望这对其他人有帮助。

于 2012-01-26T01:33:27.113 回答
1

我知道这是一个老问题,但还有另一种测试方法。添加了 Pony 1.10 版override_options。Pony 使用Mail发送电子邮件。override_options允许您使用 Mail 中内置的 TestMailer 功能。所以你可以像这样设置你的测试:

在 spec_helper

require 'pony'
Pony.override_options = { :via => :test }

在你的测试中

before do
  Mail::TestMailer.deliveries.clear
end

it 'some test' do
  # some code that generates an email
  mail = Mail::TestMailer.deliveries.last
  expect(mail.to).to eql 'some@email.com'
end
于 2016-05-24T12:02:08.367 回答