[rspec-users] Can you use RSpec to test initializers?

Scott Taylor mailing_lists at railsnewbie.com
Tue May 6 21:55:12 EDT 2008

On May 6, 2008, at 4:03 PM, Erik Pukinskis wrote:

> Hi there!
> I'm trying to spec out some code that will set the smtp_settings in a
> custom ActiveMailer object.  Basically I want to check that if my
> configuration object has the right smtp_server, that the ActiveMailer
> object gets set up correctly.  So, my spec looks like this:
>  it "uses smtp server if config says so" do
>    GitoriousConfig.should_receive(: 
> []).with('smtp_settings').and_return({
>      :address  => "smtp.postoffice.net",
>    })
>    Mailer.smtp_settings[:address].should == "smtp.postoffice.net"
>  end
> 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.

You could try using Kernel#load to load the file inside the spec, but  
you might get strange errors on the other side...

Let me know how it works out.


More information about the rspec-users mailing list