【问题标题】:How to test Mailer on Sinatra post request?如何在 Sinatra 发布请求上测试 Mailer?
【发布时间】:2013-04-15 13:28:57
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

    • 我不认为你是愚蠢的,+1。 Pony 的传递方法(或至少是公共 API 的方法) mail 方法。那应该是doubled。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-09
    • 2021-12-06
    • 2017-02-13
    • 2022-01-27
    • 2014-06-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多