Tuesday, October 6, 2009

Making ActionMailer testable

If you ever create a custom subclass of ActionMailer you'll be having a hard time to test it. That's because - by default - you cannot access the ActionMailer instance after creating a mail. To make ActionMailer testable you have to make its new-method public:

    1 class ActionMailer::Localized < ActionMailer::Base
2
3 #to make ActionMailer testable
4 public_class_method :new
5
6 private
7
8 #we would like to test that the correct template is set
9 def initialize_defaults(method_name)
10 super
11 @template = "#{I18n.locale}_#{method_name}"
12 end
13
14 end

With that change it's easy to test the initialize_defaults-method (as shown here using rspec):

    1 describe ActionMailer::Localized do
2
3 before(:each) do
4 @localized_mailer = Class.new(ActionMailer::Localized) do
5 def mailer_method(mail_object); end
6 end.new
7 @localized_mailer.stub!(:render)
8 I18n.locale = 'de'
9 end
10
11 describe 'after being initialized' do
12 before(:each) do
13 @localized_mailer.create!('mailer_method', Object.new)
14 end
15 it "should have the localized template name set" do
16 @localized_mailer.template.should == 'de_mailer_method'
17 end
18 end
19
20 end

No comments: