On Tue, May 6, 2008 at 4:03 PM, Erik P. [email protected]
Mailer.smtp_settings[:address].should == “smtp.postoffice.net”
The trouble is, the code that sets the mailer settings is in an
initializer (config/initializers/mailer.rb) and it gets run long
before my spec gets run, and so it never encounters my mock. Is there
any way I can get the initializer code to run inside my spec?
I know I could create a separate initialize method on my Mailer object
that has the initialization stuff, and call that method from both my
test and my initializer, but that seems less ideal than just calling
the initializer from the spec.
Any advice? I can’t find any information at all online about using
Rspec with initializers.
Erik, I would not test configuration settings this way. Setting up mock
expectations helps when you are talking to another object whose
implementation you don’t have yet, or don’t want the test to rely. Since
are testing configuration settings I would vote that you test against
actual configuration settings.
A quick sidebar, I don’t like setting up SMTP settings in an
prefer to do it in the correct environment/*.rb file. This is because
often don’t want your development or test environments sending out
(at least not via the same route as production).
If you do move the configuration setup from your initializer to an
environment file then what you want to test is going to be more
since it may be different for each environment. And when you run a spec
going to be executed in the test environment, which is probably not the
settings you wanted to ensure got setup. You are probably wanting to
sure the production environment runs with specific settings.
In the past I’ve foregone automated testing of my configuration
usually setup my production.rb configuration on the production server,
then every time I deploy I’m symlink that file into
RAILS_ROOT/config/environment/. This greatly reduces the risk that the
production settings is going to be modified or altered unintentionally.
Keeping snapshot backups of your production setup (or even just the
configuration files) also helps reduce risk even more. You could put
production files in their own svn or git repository so you can easily
revert back when you do make changes to those files.
If you really want to test the production settings you could right a
which loaded up the rails application in the production environment,
out the SMTP settings in YAML, and then your test could read that in
YAML.load and you could ensure the settings are what you expect.
settings = YAML.load(
RAILS_ENV=production ruby -r config/environment.rb -e "y ActionMailer::Base.smtp_settings"
settings[:domain].should == “smtp.example.com”