I recently needed to implement some tests for the
SandboxEmailInterceptor Intializer pattern suggested by the rails guide. I found two methods to test the class but neither of them are perfect.
You can test the functionality of the interceptor
test 'it should redirect email when interceptor is run' do SandboxEmailInterceptor.delivering_email(@email) assert_equal @email.to, ['firstname.lastname@example.org'] end
However, passing this test doesn’t mean your emails will be intercepted.
Stub the environment and load the initializer
test 'it sends all emails to email@example.com in staging' do Rails.stub(:env, ActiveSupport::StringInquirer.new('staging')) do load 'config/initializers/sandbox_email_interceptor.rb' @email.deliver last_email_sent = ActionMailer::Base.deliveries.last assert_equal last_email_sent.to, ['firstname.lastname@example.org'] end end
This gets us closer but if your initializers aren’t running, for example then this test will still be inadequate. I haven’t found a better solution than this one so please comment if you know of one.