Class: StimulusSpec::Matchers::HaveStimulusTarget

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

Overview

Asserts that rendered HTML contains a +data-controller-target+ attribute with the given target name.

Examples:

expect(response).to have_stimulus_target("hello", "name")

Instance Method Summary collapse

Constructor Details

#initialize(controller, target) ⇒ HaveStimulusTarget

Returns a new instance of HaveStimulusTarget.

Parameters:

  • controller (String)

    controller name

  • target (String)

    target name



12
13
14
15
16
# File 'lib/stimulus_spec/matchers/have_stimulus_target.rb', line 12

def initialize(controller, target)
  @controller = controller.to_s
  @target = target.to_s
  @attr = "data-#{@controller}-target"
end

Instance Method Details

#descriptionObject



52
53
54
# File 'lib/stimulus_spec/matchers/have_stimulus_target.rb', line 52

def description
  "have Stimulus target \"#{@target}\" for controller \"#{@controller}\""
end

#does_not_match?(subject) ⇒ Boolean

Returns:

  • (Boolean)


36
37
38
# File 'lib/stimulus_spec/matchers/have_stimulus_target.rb', line 36

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

#failure_messageObject



40
41
42
43
44
45
46
# File 'lib/stimulus_spec/matchers/have_stimulus_target.rb', line 40

def failure_message
  found_targets = @doc.css("[#{@attr}]").flat_map { |el| el[@attr].split }
  msg = "expected to find an element with #{@attr}=\"#{@target}\""
  msg += "\n  found targets: #{found_targets.uniq.map { |t| "\"#{t}\"" }.join(", ")}" if found_targets.any?
  msg += "\n  in:\n#{snippet}"
  msg
end

#failure_message_when_negatedObject



48
49
50
# File 'lib/stimulus_spec/matchers/have_stimulus_target.rb', line 48

def failure_message_when_negated
  "expected not to find an element with #{@attr}=\"#{@target}\" but found one"
end

#matches?(subject) ⇒ Boolean

Parameters:

  • subject (#body, String)

    response object or HTML string

Returns:

  • (Boolean)


27
28
29
30
31
32
33
34
# File 'lib/stimulus_spec/matchers/have_stimulus_target.rb', line 27

def matches?(subject)
  @body = extract_body(subject)
  @doc = Nokogiri::HTML5.fragment(@body)
  root = search_root
  return false unless root

  !root.at_css("[#{@attr}~='#{@target}']").nil?
end

#within(selector) ⇒ self

Parameters:

  • selector (String)

    CSS selector for the scope element

Returns:

  • (self)


20
21
22
23
# File 'lib/stimulus_spec/matchers/have_stimulus_target.rb', line 20

def within(selector)
  @scope = selector
  self
end