Skip to content

Commit

Permalink
Make sure assert_lodash_safety works
Browse files Browse the repository at this point in the history
Before this commit it was raising an error because the string
the message was being appended to was frozen.
  • Loading branch information
rafaelfranca committed Jun 28, 2023
1 parent f806ca6 commit 9b4d7bd
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/better_html/test_helper/safe_lodash_tester.rb
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ def assert_lodash_safety(data, **options)
buffer.source = data
tester = Tester.new(buffer, **options)

message = ""
message = +""
tester.errors.each do |error|
message << <<~EOL
On line #{error.location.line}
Expand Down
39 changes: 39 additions & 0 deletions test/better_html/test_helper/safe_lodash_tester_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
module BetterHtml
module TestHelper
class SafeLodashTesterTest < ActiveSupport::TestCase
include SafeLodashTester

test "interpolate in attribute not allowed" do
errors = parse(<<-EOF).errors
<div class="[%! foo %]">
Expand Down Expand Up @@ -83,6 +85,43 @@ class SafeLodashTesterTest < ActiveSupport::TestCase
assert_equal "javascript statement not allowed here; did you mean '[%=' ?", errors.first.message
end

test "assertion failure" do
error = assert_raises(Minitest::Assertion) do
assert_lodash_safety(<<-EOF)
<div class="foo[% if (foo) %]">
EOF
end

assert_equal <<~MESSAGE.chomp, error.message
On line 1
javascript statement not allowed here; did you mean '[%=' ?
<div class="foo[% if (foo) %]">
^^^^^^^^^^^^^^
-----------
The javascript snippets listed above do not appear to be escaped properly
in their context. Here are some tips:
Always use lodash's escape syntax inside a html tag:
<a href="[%= value %]">
^^^^
Always use JSON.stringify() for html attributes which contain javascript, like 'onclick',
or twine attributes like 'data-define', 'data-context', 'data-eval', 'data-bind', etc:
<div onclick="[%= JSON.stringify(value) %]">
^^^^^^^^^^^^^^
Never use <script> tags inside lodash template.
<script type="text/javascript">
^^^^^^^
-----------
.
Expected [#<BetterHtml::TestHelper::SafetyError: javascript statement not allowed here; did you mean '[%=' ?>] to be empty?.
MESSAGE
end

private

def parse(data)
Expand Down

0 comments on commit 9b4d7bd

Please sign in to comment.