Panasonic Youth rob sanheim writes about software, business, ruby, music, stuff and things



Posted
11 October 2006 @ 2pm

Tagged
Rails, Ruby, TDD

Discuss

How to Stub ActionController#render for Testing

Sometimes you just want to ensure that render will get called with the correct parameters in a test. Say, for instance, if you have your own special site_render method that examines subdomains or other info about the current request, and then does the real render based on that. This little test helper will override the render method to just return the options hash it was called with in a block, and then it will restore the original method to allow other functional tests to work correctly:

RUBY:
  1. # stub out render to just return the options hash it was called with, to make it testable
  2.   def stub_render_method
  3.     @controller.class.class_eval do 
  4.       def render(options = nil)
  5.         options
  6.       end
  7.     end
  8.     yield
  9.   ensure
  10.     @controller.class.send(:remove_method, :render)
  11.   end

Call it like so, with a made up "special_render" that takes some params and then calls render based on that:

RUBY:
  1. stub_render_method do
  2.       assert_equal({:partial => "foo/baz/about"}, @controller.special_render(:baz => true, :partial => "about"))
  3.       assert_equal({:partial => "foo/doop/about"}, @controller.special_render(:doop => true, :partial => "about"))
  4.       # bad parameter, render gets called with default params and probably an error message
  5.        assert_equal "",    @controller.special_render(:partial => "unknown_bad_parameter")
  6.     end

Easy.


1 Comment

Posted by
19892 Blog Verification
16 October 2006 @ 3am

19892 Blog Verification

19892


Leave a Comment

Introducing BrainBuster - Logic Captcha for Rails New Version of BrainBuster - 0.6