Sha256: 05734062c8ad759b3e225e675d0a689b297560b6771364e9ebea5850016fc262

Contents?: true

Size: 1.8 KB

Versions: 4

Compression:

Stored size: 1.8 KB

Contents

# frozen_string_literal: true

module ViewComponent
  module TestHelpers
    begin
      require "capybara/minitest"
      include Capybara::Minitest::Assertions

      def page
        Capybara::Node::Simple.new(@rendered_component)
      end

      def refute_component_rendered
        assert_no_selector("body")
      end
    rescue LoadError
      # We don't have a test case for running an application without capybara installed.
      # It's probably fine to leave this without coverage.
      # :nocov:
      warn "WARNING in `ViewComponent::TestHelpers`: You must add `capybara` to your Gemfile to use Capybara assertions." if ENV["DEBUG"]
      # :nocov:
    end

    attr_reader :rendered_component

    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

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

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

    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

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

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

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

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
view_component-2.30.0 lib/view_component/test_helpers.rb
view_component-2.29.0 lib/view_component/test_helpers.rb
view_component-2.28.0 lib/view_component/test_helpers.rb
view_component-2.27.0 lib/view_component/test_helpers.rb