我有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'
请求?
答案 0 :(得分:1)
也许我愚蠢,但看起来很明显 - 你的生产代码中没有任何东西可以调用deliver
方法。你不应该验证Pony.should_receive(:mail)
吗?
更新:我看到Pony有一个名为deliver的私有类方法,但是你正在使用它,所以它永远不会被调用。