[rspec-users] view.should render_template best practices?

David Chelimsky dchelimsky at gmail.com
Wed Nov 17 06:37:07 EST 2010

On Nov 16, 2010, at 8:16 AM, Matt Darby wrote:

> I've been looking for the definitive answer for months now, and the
> RSpec book doesn't touch on it at all:
> How do we now handle stubbing out rendering of partials in view specs
> in RSpec2?
> I have a large (35K+ lines of views and related specs) that I'm trying
> to upgrade to Rails3/RSpec2. My views use partials pretty extensively
> and this issue is a huge blocker for me.
> before do
>  view.should render_template("event_list", :locals => {:calendar =>
> @calendar})
> end
> causes all my related specs fail with:
> expecting <"event_list"> but rendering with <"">.
> Expected block to return true value.
> Any advice?

In rspec-2/rails-3, view.should render_template("event_list") is no longer a message expectation (pre-action), but rather delegates to Rails' assert_template method, so it needs to come _after_ the action. It should work exactly as you have it above, just after the action.

This is documented in the rspec-rails README (https://github.com/rspec/rspec-rails - see sections on View Specs and Matchers), though not with an upgrade note pointing out that it changed. I'll make that addition shortly.

As for stubbing the template, so that it is not actually rendered, RSpec doesn't offer a way to do this in view specs and I don't think Rails does either. I added an issue for this (https://github.com/rspec/rspec-rails/issues/issue/263), and hopefully we'll be able to resolve it soon. In the mean time, the examples will need to supply any data needed by the template being spec'd _and_ any of the partials.

Side note: I urge you not to put message expectations (pre "When") or state-based expectations (post "When") in before/after blocks. It makes examples difficult to understand, and results in specifying the same things in every example in a group. Rather, have one example that specifies each individual thing. In this case:

  it "renders the event_list with @calendar" do
    view.should render_template(
      :locals => {:calendar => @calendar}

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://rubyforge.org/pipermail/rspec-users/attachments/20101117/964b03d8/attachment.html>

More information about the rspec-users mailing list