rspec_on_rails render_and_receive_matcher
on November 14, 2007 @ 12:10 AM
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:
1 2 3 4 5 |
it "displays foo" do template.should_receive(:bar).with(@foo).and_return(%|<p id='bar'></p>|) render_it response.should have_tag("p#bar") end |
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:
1 2 3 4 5 |
it "displays foo" do during_render do template.should receive_and_render(:bar).with(@foo) end end |
The receive_and_render method sets up a should_receive 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 \ http://continuous.rubyforge.org/svn/trunk/rspec/matchers/rspec_on_rails_render_and_receive
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!


3 comments
Jump to comment form | comments rss [?]