【问题标题】:Testing Email w/ Pony and RSpec in Rails 3.1在 Rails 3.1 中使用 Pony 和 RSpec 测试电子邮件
【发布时间】:2016-05-24 20:02:08
【问题描述】:

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

spec/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| (小马).mail(任何参数) 预计:1次 收到:0次 # ./spec/controllers/users_controller_spec.rb:121:in `block (4 levels) in '

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

有什么想法吗?

【问题讨论】:

    标签: ruby-on-rails-3 rspec pony


    【解决方案1】:

    这是我最终测试的结果......

    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 是在设置后完成的。

    希望这对其他人有所帮助。

    【讨论】:

      【解决方案2】:

      我知道这是一个老问题,但还有另一种测试方法。 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
      

      【讨论】:

        猜你喜欢
        • 2012-01-20
        • 1970-01-01
        • 2012-01-24
        • 1970-01-01
        • 1970-01-01
        • 2017-04-10
        • 2015-05-28
        • 2011-11-19
        • 1970-01-01
        相关资源
        最近更新 更多