views:

223

answers:

1

I have this in my application_helper.rb:

def bbcode(text)
  # Code snippets
  text.gsub!(/\[code=?["']?(.*?)["']?\](.*?)\[\/code\]/mis) { CodeRay.scan($2.strip, $1.to_sym).div(:line_numbers => :table)}
  text = sanitize(text, :tags => %w(span div table tr td br pre tt), :attributes => %w(id class style))
  # Gist embedding
  text.gsub!(/\[gist\](.*?)\[\/gist\]/) { $1.split(" ").map { |gist| "<script src='http://gist.github.com/#{gist}.js'&gt;&lt;/script&gt;" } }

  # allows for nested quotes
  bbquote(text)

  # non-attributed quote
  text.gsub!(/\[quote\](.*?)\[\/quote\]/mis) { "<div class='center'><div class='quote'>" << $1 << "</div></div>" }

  # Terminal example
  text.gsub!(/\[term\](.*?)\[\/term\]/mi) { "<span class='term'>" << $1.gsub(/^\r\n/,"").gsub("<","&lt;").gsub(">","&gt;") << "</span>" }

  # URLs
  text.gsub!(/\[url=["']?(.*?)["']?\](.*?)\[\/url\]/mis) { "<a rel='nofollow' href='" << $1 << "'>" << $2 << "</a>" }

  # handle with care...
  bbcode_ext(text)
end

As a good Rails developer, I've attempted to write a test for this method:

require File.dirname(__FILE__) + '/../spec_helper'
describe ApplicationHelper, "general" do
  include ApplicationHelper
  it "should correctly encapsulate double quotes" do
    bbcode('[quote="Kitten"][quote="Dog"]QUOTE INSIDE[/quote]QUOTE OUTSIDE[/quote]').should eql("<div class='center'><div class='quote'><b>Kitten wrote:</b><div class='center'><div class='quote'><b>Dog wrote:</b></div></div>QUOTE OUTSIDE</div></div>")
  end
end

When I go to run this test however I get this error undefined method 'white_list_sanitizer' for Spec::Rails::Example::HelperExampleGroup::Subclass_1:Class

This is because Spec::Rails::Example::HelperExampleGroup::Subclass_1:Class != ActionView::Base. How do I test this code that uses the sanitize method?

+1  A: 

Mixin specs assume you want to test the mixin in isolation - so the mix in is mixed in to the spec and you would need to mock any methods they expect to be there. So in this case you could mock 'sanitize'

However, here it looks like you actually want to test that calling sanitize the way you have results in the behavior you want, so you don't want to test your helper in isolation, but in integrated with a view object...

So, create an object that extends ActionView::Base in your spec, mixin your helper and then run your specs on that object

class AView < ActionView::Base
   include ApplicationHelper
end

describe AView, "general" do

  it "should correctly encapsulate double quotes" do
    AView.new.bbcode('[quote="Kitten"][quote="Dog"]QUOTE INSIDE[/quote]QUOTE OUTSIDE[/quote]').should eql("<div class='center'><div class='quote'><b>Kitten wrote:</b><div class='center'><div class='quote'><b>Dog wrote:</b></div></div>QUOTE OUTSIDE</div></div>")
  end
end
Perryn Fowler
Works, many thanks!
Ryan Bigg