gpt4 book ai didi

ruby-on-rails - 如何在 Sinatra post 请求上测试 Mailer?

转载 作者:太空宇宙 更新时间:2023-11-03 16:30:59 25 4
gpt4 key购买 nike

我有 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' 请求?

最佳答案

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

更新:我看到 Pony 有一个名为 deliver 的私有(private)类方法,但你将其 stub ,因此它永远不会被调用。

关于ruby-on-rails - 如何在 Sinatra post 请求上测试 Mailer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16016422/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com