[rspec-users] RSpec 2 view specs: partial mocks

David Chelimsky dchelimsky at gmail.com
Sun Jun 20 17:48:36 EDT 2010

On Jun 20, 2010, at 3:19 PM, Michael Schuerig wrote:

> Are partial mocks supposed to work in rails-rspec 2.0.0.beta.12?
> I'm trying to do things like
>  view.stub(:current_user).and_return(@user)
>  view.stub(:current_page?).and_return(false)
> However, when I do that, the view uses its "ordinary" functionality, in 
> particular, assigns are no longer available as instance variables.

Are you using rails beta 4? Before that release, the view() method returned a different object every time.

> Also, as regards mocking of partials (the rails ones)
>  view.should_receive(:_render_partial).
>    with(hash_including(:partial => "widget/row"))
> does not work as expected when render is called with objects like this
>  render @article
>  render @articles
> In these cases the hash[:partial] does not contain the path to the 
> template, but the object(s).

view.should_receive(:anything_at_all) is specifying rails internals, and has to be 100% precise. In this case, what you need to do is pretty invasive, and I wouldn't recommend it, but here it is:

require 'spec_helper'

describe "widgets/index.html.erb" do
  before(:each) do
    @widgets = assign(:widgets, [

  it "renders a list of widgets" do
    view.should_receive(:_render_partial).with(hash_including(:partial => @widgets[0]))
    view.should_receive(:_render_partial).with(hash_including(:partial => @widgets[1]))


Can I hear a "blech!!!!!!!!!!!!".

Unfortunately, there is not a better way to do this yet, and there may not be for some time. One of the big wins of rspec-rails-2 over rspec-rails-1 is that it does not rely on monkey patches (except in cases in which rails has changed since the last rails release, but rspec-rails needs to work with the last release). This drastically reduces the likelihood that rails releases will break rspec, which has been a big pain-point in the past.

The downside of this is that we have to live with what Rails has to offer, and view tests are not nearly as robust as controller tests in rails. Yet :)


> I'm right now having little fun in beta hell. That's just how it is and 
> by no means intend to distract you from your good work. I'm not yet 
> reasonably familiar with Rails 3 and RSpec 2 and so I'm stumbling around 
> alot in the sources and inch along in the debugger. One repeating point 
> of bother is that often stacktraces are barely informative when 
> delegation and dynamically generated code are in there. Unfortunately, I 
> can't think of a way to improve on this.
> Michael
> -- 
> Michael Schuerig
> mailto:michael at schuerig.de
> http://www.schuerig.de/michael/
> _______________________________________________
> rspec-users mailing list
> rspec-users at rubyforge.org
> http://rubyforge.org/mailman/listinfo/rspec-users

More information about the rspec-users mailing list