Skip to content

Commit

Permalink
Add possibility to test HTML attribute selectors
Browse files Browse the repository at this point in the history
Previously it wasn't possible to test something like this:

```
assert_select_jquery :remove, "[data-placeholder~=name]"
```

This commit fixes it by escaping `[` and `]` characters in the selector.
  • Loading branch information
mrhead committed Nov 2, 2016
1 parent 47d1512 commit d4dd8cd
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 2 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
## 4.2.2

- Add possibility to test HTML attribute selectors

## 4.2.1

- Update jQuery to 3.1.0
Expand Down
13 changes: 11 additions & 2 deletions lib/jquery/assert_select.rb
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,9 @@ module Rails::Dom::Testing::Assertions::SelectorAssertions
def assert_select_jquery(*args, &block)
jquery_method = args.first.is_a?(Symbol) ? args.shift : nil
jquery_opt = args.first.is_a?(Symbol) ? args.shift : nil
id = args.first.is_a?(String) ? args.shift : nil
id = args.first.is_a?(String) ? escape_id(args.shift) : nil

target_pattern = "['\"]#{id || '.*'}['\"]"
target_pattern = "['\"\\[]#{id || '.*'}['\"\\]]"
method_pattern = "#{jquery_method || '\\w+'}"
argument_pattern = jquery_opt ? "['\"]#{jquery_opt}['\"].*" : PATTERN_HTML

Expand Down Expand Up @@ -128,4 +128,13 @@ def unescape_js(js_string)
unescaped.gsub!(PATTERN_UNICODE_ESCAPED_CHAR) {|u| [$1.hex].pack('U*')}
unescaped
end

def escape_id(selector)
return unless selector

id = selector.gsub('[', '\[')
id.gsub!(']', '\]')

id
end
end
2 changes: 2 additions & 0 deletions test/assert_select_jquery_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ class AssertSelectJQueryTest < ActiveSupport::TestCase
jQuery("<div><p>something</p></div>").prependTo("#id");
$('#id').remove();
jQuery("#id").hide();
$("[data-placeholder~=name]").remove();
JS

setup do
Expand All @@ -28,6 +29,7 @@ def test_target_as_receiver
assert_select_jquery :replaceWith, '#id' do
assert_select 'p', 'something'
end
assert_select_jquery :remove, "[data-placeholder~=name]"
end

assert_raise Minitest::Assertion, "No JQuery call matches [:show, :some_wrong]" do
Expand Down

0 comments on commit d4dd8cd

Please sign in to comment.