RSpec匿名邮件?

时间:2014-10-01 04:39:35

标签: ruby-on-rails rspec

RSpec有一个anonymous controller,可以方便地测试" base"其他控制器的控制器,请看这个例子:

应用程序/控制器/管理/ base_controller.rb

class Admin::BaseController < ApplicationController
  before_action :authenticate_user!
  before_action :admin_required

  layout 'admin'

  private

    def admin_required
      render text: 'Unauthorized', status: :unauthorized unless current_user.admin?
    end
end

规格/控制器/管理/ base_controller_spec.rb

require 'rails_helper'

RSpec.describe Admin::BaseController, :type => :controller do
  controller do
    def index
      head :ok
    end
  end

  describe '#index' do
    def do_request
      get :index
    end

    context "as non-admin" do
      before { sign_in create(:user) }

      it 'raises error' do
        do_request
        expect(response).to have_http_status(:unauthorized)
        expect(response).not_to be_success
      end
    end

    context "as admin" do
      before { sign_in create(:user, :with_admin) }

      it 'does not raise error' do
        do_request
        expect(response).to be_success
      end
    end
  end
end

我的邮件使用了类似的结构。

我当前的实施需要我向test添加BaseMailer并为该test方法添加相应的视图。

有没有办法实现某种匿名邮件程序测试?类似的东西:

应用程序/邮寄者/ base_mailer.rb

class BaseMailer < ActionMailer::Base
  layout 'mailer'

  default from:     'Support <support@example.com>',
          reply_to: 'Support <support@example.com>',
end

规格/邮寄者/ base_mailer_spec.rb

require 'rails_helper'

RSpec.describe Admin::BaseController, :type => :mailer do
  mailer do # <= Anonymous mailer!
    def test
      mail
    end
  end

  describe '#welcome' do
    let(:email) { email_to }

    def email_to
      mailer.test # <= Anonymous mailer!
    end

    it { expect(email).to deliver_from 'Support <support@example.com>' }
    it { expect(email).to     reply_to 'Support <support@example.com>' }
  end
end

然后我可以摆脱testapp/views/base_mailer/test.html.erb文件,我从未使用它,只是用于测试。

谢谢!

P.S。此邮件程序测试语法来自:https://github.com/bmabey/email-spec

1 个答案:

答案 0 :(得分:2)

可以实现,请参阅this comment

RSpec.describe BaseMailer do
  mailer = Class.new(BaseMailer) do
    def a_sample_email
      # We need a body to not render views
      mail(body: '')
    end
  end

  it 'has the default "from" address' do
    email = mailer.a_sample_email
    expect(email.from).to eq 'Support <support@example.com>'
  end
end

来源:https://github.com/rspec/rspec-rails/issues/1182