Skip to content

Instantly share code, notes, and snippets.

@earnold
Created August 29, 2011 21:25
Show Gist options
  • Save earnold/1179448 to your computer and use it in GitHub Desktop.
Save earnold/1179448 to your computer and use it in GitHub Desktop.
Matchers for sanitize-rails
module Sanitize::Rails
module RSpecHelpers
class << self
def setup(sanitization_couplets)
@@sanitization_couplets = sanitization_couplets
end
def sanitization_couplets
@@sanitization_couplets
end
end
end
end
RSpec::Matchers.define :sanitize_attributes do |*attributes|
match do |model|
matches = true
sanitizer = Sanitize::Rails::Engine.method_for(attributes)
attributes.each do |attribute|
Sanitize::Rails::RSpecHelpers.sanitization_couplets.each do |unsanitary_value, sanitariy_value|
model.send("#{attribute}=", unsanitary_value)
model.send sanitizer
unless model.send(attribute) == sanitariy_value
@unmatched_unsanitary_value = unsanitary_value
@unmatched_sanitary_value = sanitariy_value
@actual_value = model.send(attribute)
@unsanitary_attribute = attribute
matches = false
break
end
end
break unless matches
end
matches
end
failure_message_for_should do
"for #{@unsanitary_attribute}, expected that #{@unmatched_unsanitary_value} would be sanitized to #{@unmatched_sanitary_value}, but got #{@actual_value}"
end
end
Sanitize::Rails::RSpecHelpers.setup({
"<script>hi!</script>" => "hi!",
"<a onmouseover='alert(\"hi!\");'>http://github.com</a>" => "<a rel=\"nofollow\">http://github.com</a>",
"<b>hi!</b>" => "<b>hi!</b>"
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment