Class: StimulusSpec::Matchers::HaveStimulusController

Inherits:
Object
  • Object
show all
Defined in:
lib/stimulus_spec/matchers/have_stimulus_controller.rb

Instance Method Summary collapse

Constructor Details

#initialize(*names) ⇒ HaveStimulusController

Returns a new instance of HaveStimulusController.



6
7
8
# File 'lib/stimulus_spec/matchers/have_stimulus_controller.rb', line 6

def initialize(*names)
  @names = names.map(&:to_s)
end

Instance Method Details

#descriptionObject



45
46
47
48
# File 'lib/stimulus_spec/matchers/have_stimulus_controller.rb', line 45

def description
  label = @names.map { |n| "\"#{n}\"" }.join(", ")
  "have Stimulus controller #{label}"
end

#does_not_match?(subject) ⇒ Boolean

Returns:

  • (Boolean)


26
27
28
# File 'lib/stimulus_spec/matchers/have_stimulus_controller.rb', line 26

def does_not_match?(subject)
  !matches?(subject)
end

#failure_messageObject



30
31
32
33
34
35
36
37
38
# File 'lib/stimulus_spec/matchers/have_stimulus_controller.rb', line 30

def failure_message
  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_negatedObject



40
41
42
43
# File 'lib/stimulus_spec/matchers/have_stimulus_controller.rb', line 40

def failure_message_when_negated
  label = @names.map { |n| "\"#{n}\"" }.join(", ")
  "expected not to find an element with data-controller=#{label} but found one"
end

#matches?(subject) ⇒ Boolean

Returns:

  • (Boolean)


15
16
17
18
19
20
21
22
23
24
# File 'lib/stimulus_spec/matchers/have_stimulus_controller.rb', line 15

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) ⇒ Object



10
11
12
13
# File 'lib/stimulus_spec/matchers/have_stimulus_controller.rb', line 10

def within(selector)
  @scope = selector
  self
end