Class: TurboRspec::Matchers::HaveStimulusTarget

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

Overview

RSpec matcher for asserting that a response body contains an element with the given Stimulus target (+data-controller-target+ contains the target name as a space-separated token).

Examples:

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

Instance Method Summary collapse

Constructor Details

#initialize(controller_name, target_name) ⇒ HaveStimulusTarget

Returns a new instance of HaveStimulusTarget.



15
16
17
18
# File 'lib/turbo_rspec/matchers/have_stimulus_target.rb', line 15

def initialize(controller_name, target_name)
  @controller_name = controller_name.to_s
  @target_name = target_name.to_s
end

Instance Method Details

#descriptionString

Returns:

  • (String)


44
45
46
# File 'lib/turbo_rspec/matchers/have_stimulus_target.rb', line 44

def description
  "have Stimulus target #{@target_name.inspect} for #{@controller_name.inspect}"
end

#does_not_match?(response_or_body) ⇒ Boolean

Parameters:

  • response_or_body (#body, String)

Returns:

  • (Boolean)


29
30
31
# File 'lib/turbo_rspec/matchers/have_stimulus_target.rb', line 29

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

#failure_messageString

Returns:

  • (String)


34
35
36
# File 'lib/turbo_rspec/matchers/have_stimulus_target.rb', line 34

def failure_message
  "expected response to have Stimulus target #{@target_name.inspect} for controller #{@controller_name.inspect}"
end

#failure_message_when_negatedString

Returns:

  • (String)


39
40
41
# File 'lib/turbo_rspec/matchers/have_stimulus_target.rb', line 39

def failure_message_when_negated
  "expected response not to have Stimulus target #{@target_name.inspect} for controller #{@controller_name.inspect}"
end

#matches?(response_or_body) ⇒ Boolean

Parameters:

  • response_or_body (#body, String)

Returns:

  • (Boolean)


22
23
24
25
# File 'lib/turbo_rspec/matchers/have_stimulus_target.rb', line 22

def matches?(response_or_body)
  @body = extract_body(response_or_body)
  Nokogiri::HTML5.fragment(@body).css("[data-#{@controller_name}-target~='#{@target_name}']").any?
end