Module: ViewComponent::TestHelpers

Included in:
TestCase
Defined in:
lib/view_component/test_helpers.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#rendered_componentObject (readonly)

Returns the value of attribute rendered_component.



24
25
26
# File 'lib/view_component/test_helpers.rb', line 24

def rendered_component
  @rendered_component
end

Instance Method Details

#build_controller(klass) ⇒ Object



63
64
65
# File 'lib/view_component/test_helpers.rb', line 63

def build_controller(klass)
  klass.new.tap { |c| c.request = request }.extend(Rails.application.routes.url_helpers)
end

#controllerObject



37
38
39
# File 'lib/view_component/test_helpers.rb', line 37

def controller
  @controller ||= build_controller(Base.test_controller.constantize)
end

#render_inline(component, **args, &block) ⇒ Object



26
27
28
29
30
31
32
33
34
35
# File 'lib/view_component/test_helpers.rb', line 26

def render_inline(component, **args, &block)
  @rendered_component =
    if Rails.version.to_f >= 6.1
      controller.view_context.render(component, args, &block)
    else
      controller.view_context.render_component(component, &block)
    end

  Nokogiri::HTML.fragment(@rendered_component)
end

#requestObject



41
42
43
# File 'lib/view_component/test_helpers.rb', line 41

def request
  @request ||= ActionDispatch::TestRequest.create
end

#with_controller_class(klass) ⇒ Object



54
55
56
57
58
59
60
61
# File 'lib/view_component/test_helpers.rb', line 54

def with_controller_class(klass)
  old_controller = defined?(@controller) && @controller

  @controller = build_controller(klass)
  yield
ensure
  @controller = old_controller
end

#with_variant(variant) ⇒ Object



45
46
47
48
49
50
51
52
# File 'lib/view_component/test_helpers.rb', line 45

def with_variant(variant)
  old_variants = controller.view_context.lookup_context.variants

  controller.view_context.lookup_context.variants = variant
  yield
ensure
  controller.view_context.lookup_context.variants = old_variants
end