[rspec-users] Can I construct the controller myself in a controller spec?

Pat Maddox pat.maddox at gmail.com
Thu Mar 5 01:47:00 EST 2009


On Wed, Mar 4, 2009 at 8:38 PM, Perryn Fowler <pezlists at gmail.com> wrote:
> Hi
>
> I am experimenting with Constructor based dependency injection for
> rails controllers.
>
> So I have something like this
>
> class LoginSessionsController < ApplicationController
>
>  def initialize(authenticator =  TheRealAuthenticator)
>    @authenticator = authenticator
>  end
>
>  ....
> end
>
>
> The plan was to override the authenticator used when testing with something like
>
> describe LoginSessionsController.new(MyMockAuthenticator) do
>   ......
> end
>
> but rspec seems to insist on constructing the controller itself
>
> Is there a way to do this I am missing?
> _______________________________________________
> rspec-users mailing list
> rspec-users at rubyforge.org
> http://rubyforge.org/mailman/listinfo/rspec-users
>

It'd be badass, but, basically, no.  Instantiating a controller in
Rails takes a lot of work - request/response objects, routes, and the
code that does so is a big mess.

You could use factory methods, and then stub that method in your examples:

class LoginSessionsController < ApplicationController
  def authenticator
    TheRealAuthenticator
  end
end

describe LoginSessionsController do
  before(:each) do
    controller.stub!(:authenticator).and_return MockAuthenticator
  end
end

Pat


More information about the rspec-users mailing list