Class: StimulusSpec::Matchers::HaveStimulusController
- Inherits:
-
Object
- Object
- StimulusSpec::Matchers::HaveStimulusController
- Defined in:
- lib/stimulus_spec/matchers/have_stimulus_controller.rb
Overview
Asserts that rendered HTML contains a +data-controller+ attribute with the given name(s).
Instance Method Summary collapse
- #description ⇒ Object
- #does_not_match?(subject) ⇒ Boolean
- #failure_message ⇒ Object
- #failure_message_when_negated ⇒ Object
-
#initialize(*names) ⇒ HaveStimulusController
constructor
A new instance of HaveStimulusController.
- #matches?(subject) ⇒ Boolean
-
#within(selector) ⇒ self
Restricts matching to descendants of the given CSS selector.
Constructor Details
#initialize(*names) ⇒ HaveStimulusController
Returns a new instance of HaveStimulusController.
16 17 18 |
# File 'lib/stimulus_spec/matchers/have_stimulus_controller.rb', line 16 def initialize(*names) @names = names.map(&:to_s) end |
Instance Method Details
#description ⇒ Object
61 62 63 64 |
# File 'lib/stimulus_spec/matchers/have_stimulus_controller.rb', line 61 def description label = @names.map { |n| "\"#{n}\"" }.join(", ") "have Stimulus controller #{label}" end |
#does_not_match?(subject) ⇒ Boolean
42 43 44 |
# File 'lib/stimulus_spec/matchers/have_stimulus_controller.rb', line 42 def does_not_match?(subject) !matches?(subject) end |
#failure_message ⇒ Object
46 47 48 49 50 51 52 53 54 |
# File 'lib/stimulus_spec/matchers/have_stimulus_controller.rb', line 46 def label = @names.map { |n| "\"#{n}\"" }.join(", ") msg = "expected to find an element with data-controller=#{label}" if @found_controllers&.any? msg += "\n found controllers: #{@found_controllers.uniq.map { |c| "\"#{c}\"" }.join(", ")}" end msg += "\n in:\n#{snippet}" msg end |
#failure_message_when_negated ⇒ Object
56 57 58 59 |
# File 'lib/stimulus_spec/matchers/have_stimulus_controller.rb', line 56 def label = @names.map { |n| "\"#{n}\"" }.join(", ") "expected not to find an element with data-controller=#{label} but found one" end |
#matches?(subject) ⇒ Boolean
31 32 33 34 35 36 37 38 39 40 |
# File 'lib/stimulus_spec/matchers/have_stimulus_controller.rb', line 31 def matches?(subject) @body = extract_body(subject) @doc = Nokogiri::HTML5.fragment(@body) root = search_root return false unless root @found_controllers = root.css("[data-controller]").flat_map { |el| el["data-controller"].split } selector = @names.map { |n| "[data-controller~='#{n}']" }.join !root.at_css(selector).nil? end |
#within(selector) ⇒ self
Restricts matching to descendants of the given CSS selector.
24 25 26 27 |
# File 'lib/stimulus_spec/matchers/have_stimulus_controller.rb', line 24 def within(selector) @scope = selector self end |