Class: StimulusSpec::Matchers::HaveStimulusAction

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

Overview

Asserts that rendered HTML contains a +data-action+ attribute with the given descriptor.

Examples:

Full descriptor

expect(response).to have_stimulus_action("click->hello#greet")

Shorthand (any event)

expect(response).to have_stimulus_action("hello#greet")

Instance Method Summary collapse

Constructor Details

#initialize(descriptor) ⇒ HaveStimulusAction

Returns a new instance of HaveStimulusAction.

Parameters:

  • descriptor (String)

    full (+event->controller#method+) or shorthand (+controller#method+) descriptor



13
14
15
# File 'lib/stimulus_spec/matchers/have_stimulus_action.rb', line 13

def initialize(descriptor)
  @descriptor = descriptor.to_s
end

Instance Method Details

#descriptionObject



55
56
57
# File 'lib/stimulus_spec/matchers/have_stimulus_action.rb', line 55

def description
  "have Stimulus action \"#{@descriptor}\""
end

#does_not_match?(subject) ⇒ Boolean

Returns:

  • (Boolean)


39
40
41
# File 'lib/stimulus_spec/matchers/have_stimulus_action.rb', line 39

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

#failure_messageObject



43
44
45
46
47
48
49
# File 'lib/stimulus_spec/matchers/have_stimulus_action.rb', line 43

def failure_message
  found_actions = @doc.css("[data-action]").flat_map { |el| el["data-action"].split }
  msg = "expected to find an element with data-action=\"#{@descriptor}\""
  msg += "\n  found actions: #{found_actions.uniq.map { |a| "\"#{a}\"" }.join(", ")}" if found_actions.any?
  msg += "\n  in:\n#{snippet}"
  msg
end

#failure_message_when_negatedObject



51
52
53
# File 'lib/stimulus_spec/matchers/have_stimulus_action.rb', line 51

def failure_message_when_negated
  "expected not to find an element with data-action=\"#{@descriptor}\" but found one"
end

#matches?(subject) ⇒ Boolean

Parameters:

  • subject (#body, String)

    response object or HTML string

Returns:

  • (Boolean)


26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/stimulus_spec/matchers/have_stimulus_action.rb', line 26

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

  if @descriptor.include?("->")
    !root.at_css("[data-action~='#{@descriptor}']").nil?
  else
    !root.at_css("[data-action*='#{@descriptor}']").nil?
  end
end

#within(selector) ⇒ self

Parameters:

  • selector (String)

    CSS selector for the scope element

Returns:

  • (self)


19
20
21
22
# File 'lib/stimulus_spec/matchers/have_stimulus_action.rb', line 19

def within(selector)
  @scope = selector
  self
end