2

我有 Sinatra 应用程序,可根据邮寄请求发送电子邮件:

post '/test_mailer' do
  Pony.mail(
    to: 'me@mine.com.au',
    from: 'me@mine.com.au',
    subject: 'Howdy!',
    body: erb(:body) )
end

所以我想使用以下方法测试这种行为:

require 'spec_helper'

describe 'App' do
  before(:each) do
    Pony.stub!(:deliver)
  end

  it "sends mail" do
    Pony.should_receive(:mail) do |mail|
      mail.to.should == [ 'joe@example.com' ]
      mail.from.should == [ 'sender@example.com' ]
      mail.subject.should == 'hi'
      mail.body.should == 'Hello, Joe.'
    end

    Pony.mail(to: 'joe@example.com', from: 'sender@example.com', subject: 'hi', body: 'Hello, Joe.')
  end

  it 'test_mailer' do
    Pony.should_receive(:mail) do |mail|
        mail.to.should == ['me@mine.com.au']
    end
    post '/test_mailer'
  end

end

这是我的spec_helper

require File.join(File.dirname(__FILE__), '..', 'app.rb')

require 'sinatra'
require 'rack/test'

# setup test environment
set :environment, :test
set :run, false
set :raise_errors, true
set :logging, false

def app
  Sinatra::Application
end

RSpec.configure do |config|
  config.include Rack::Test::Methods
end

但我收到错误:

mailer(master)» rspec spec/app_spec.rb
.F

Failures:

  1) App test_mailer
     Failure/Error: Pony.should_receive(:mail) do |mail|
       (Pony).deliver(any args)
           expected: 1 time
           received: 0 times
     # ./spec/app_spec.rb:20:in `block (2 levels) in <top (required)>'

Finished in 0.02542 seconds
2 examples, 1 failure

Failed examples:

rspec ./spec/app_spec.rb:19 # App test_mailer

那么,我应该如何正确测试该post '/test_mailer'请求?

4

1 回答 1

1

也许我很愚蠢,但它看起来很明显 - 你的生产代码中没有任何东西调用deliver方法。不应该验证Pony.should_receive(:mail)吗?

更新:我看到 Pony 有一个名为 Deliver 的私有类方法,但你正在存根,所以它永远不会被调用。

于 2013-04-15T17:56:29.547 回答