使用消毒测试

时间:2009-08-23 00:48:21

标签: ruby-on-rails ruby

我在 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'></script>" } }

  # 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

作为一名优秀的Rails开发人员,我试图为这种方法编写一个测试:

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  

当我去运行此测试时,我收到此错误undefined method 'white_list_sanitizer' for Spec::Rails::Example::HelperExampleGroup::Subclass_1:Class

这是因为Spec::Rails::Example::HelperExampleGroup::Subclass_1:Class!= ActionView::Base。如何测试使用sanitize方法的代码?

1 个答案:

答案 0 :(得分:1)

Mixin规范假设您希望单独测试mixin - 因此混合使用与规范混合,您需要模拟他们期望在那里的任何方法。所以在这种情况下你可以模仿'清理'

但是,在这里看起来你实际上想要测试那个调用sanitize的方式你得到你想要的行为的结果,所以你不想孤立地测试你的帮助,而是与视图对象集成。

因此,创建一个在您的规范中扩展ActionView :: Base的对象,混合您的帮助器,然后在该对象上运行您的规范

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