RSpec有一个anonymous controller,可以方便地测试" base"其他控制器的控制器,请看这个例子:
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
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
方法添加相应的视图。
有没有办法实现某种匿名邮件程序测试?类似的东西:
class BaseMailer < ActionMailer::Base
layout 'mailer'
default from: 'Support <support@example.com>',
reply_to: 'Support <support@example.com>',
end
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
然后我可以摆脱test
和app/views/base_mailer/test.html.erb
文件,我从未使用它,只是用于测试。
谢谢!
P.S。此邮件程序测试语法来自:https://github.com/bmabey/email-spec
答案 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