rspec_on_rails render_and_receive_matcher 14 Nov 2007
Earlier today my pair and I saw a repetitious pattern in our view specs when we were using helpers. It looked similar to the following:

it "displays foo" do
   template.should_receive(:bar).with(@foo).and_return(%|<p id='bar'></p>|)
   response.should have_tag("p#bar")

The repetition was in the three lines:

  • setup a simple should receive and return
  • make the call to render
  • verify the response had the returned element

Tonight I spent some time spiking a way to cure this repetition. I’m a bigger fan of verbosity in specs over DRYness, but I think my exploration gives us something good. The above example now looks like:

it "displays foo" do
   during_render do
     template.should receive_and_render(:bar).with(@foo)

The receive_and_render method sets up a shouldreceive_ expectation on the template. For completeness there is also a stub_and_render method. As you might guess this method sets up a stub! on the template.

This doesn’t just work on the template object. It works on any object, but you should probably only use it on objects that show up in the view.

script/plugin install

script/plugin install \

Final Thoughts

This in an experiment. As I am learning more about the spirit of rspec and it’s organization there are a few things I want to change with this. Right now this is implemented as a matcher which doesn’t feel quite right, but time will tell. So in the meantime… Happy rubying!

blog comments powered by Disqus