Stubbing/Mocking a Partial Within a Partial with RSpec

10 Apr 2007

So in a previous post I complained about not being able to mock/stub a partial from within a partial, but with Peter Ryan and Mike Ward’s help we got it all figured out.
Normally in your test(spec) you call a partial like this:

render :partial => ‘partial_name’,
locals => {:page_variable => mock_page_variable }

But if you want to intercept all or some calls to render with partial, them you can’t do that. But what you can do is call a partial like so:

render ‘_partial_name’

If you need some locals you can stub them out like so:

@controller.template.stub!(:page_variable).
and_return(mock_page_variable)
render ‘_partial_name’

So if I wanted to stub out all calls to render, and assert that the string “Blargh” appears on the page, it would look a little something like this:

@controller.template.stub!(:render)
@controller.template.stub!(:page_variable).
and_return(mock_page_variable)
render ‘_partial_name’

response.body.should include(“Blargh”)

Now why does that work while “render :partial =>…” does not? I, uh, really don’t know. Ideas?