RSpec for View Helpers

  • To test a view helper, you need to test the plugin in the context of a rails app
  • To verify that you can put the following code into your spec_helper.rb (or just use rspec-plugin-generator by Pat Maddox which will generate this code for you)
      require File.dirname(__FILE__) + '/../../../../spec/spec_helper'
    rescue LoadError
      puts "You need to install rspec in your base app"
  • By convention, helper examples live in spec/helpers/ then their dependencies will get magically included.   David Chelimsky notes

    All directories under spec/ are potentially magic – rspec will always
    look at spec/:directory/:filename and see if it has an example group
    type registered for whatever directory is. So if there *is* a foo
    example group type, it will be used for any spec file in spec/foos

  • If you put helpers elsewhere, then you need to declare their type (or manually include dependencies)
    describe AppletHelper, :type => :helper do
  • To send params in your test, you can just define them before calling your view helper.  For example:
    describe DogHelper do
      it "should bark" do
        params[:debug] = "foo"
        html = helper.bark
        html.should have_tag("script")

What do you do when some behavior depends on RAILS_ENV?

  • It’s not a good practice to switch around RAILS_ENV in the test framework
  • Better idea is use a method to check it and then stub that out
  • Here’s an outline:  gist from Zach
  • Here’s what I did: EnvChecker, code and example

Stub tip

If you stub something and it appears not to be working, check when your module, class or method is loaded or created.  Dynamic languages can be challenging.  (thanks David)


For more information, see

These lessons learned while developing RSpec examples for a bug fix in openlaszlo_plugin with help from Zach Moazeni, RailsBridge mentor, and David Chelmsky, on the RSpec forum.

Leave a reply

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>