Module: Coco::TestHelpers

Defined in:
lib/coco/test_helpers.rb

Constant Summary collapse

NESTED_TAG_ATTRS =
%w[data test_data x]

Instance Method Summary collapse

Instance Method Details

#assert_component_selector(name, text: nil, visible: nil) ⇒ Object



11
12
13
# File 'lib/coco/test_helpers.rb', line 11

def assert_component_selector(name, text: nil, visible: nil, **)
  assert_selector(component_selector(name, **), text: text, visible: visible)
end

#build_attr_selector(attrs) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/coco/test_helpers.rb', line 20

def build_attr_selector(attrs)
  tag_attrs = attrs.except(*NESTED_TAG_ATTRS)
  NESTED_TAG_ATTRS.each do |key|
    subattrs = attrs.fetch(key, {})
    tag_attrs.merge!(prefix_keys(subattrs, key))
  end
  attrs.reduce("") do |str, (key, value)|
    if value.is_a?(Hash)
      value.each do |k, v|
        str += "[#{key}-#{k}='#{v}']"
      end
    else
      str += "[#{key}='#{value}']"
    end
    str
  end
end

#component_selector(name, **opts) ⇒ Object



15
16
17
18
# File 'lib/coco/test_helpers.rb', line 15

def component_selector(name, **opts)
  attr_selector = build_attr_selector(opts.except(:append, :tag))
  "#{opts[:tag]}[data-component='#{name}']#{attr_selector}#{opts[:append]}".strip
end

#create_class(name, parent) ⇒ Object



5
6
7
8
9
# File 'lib/coco/test_helpers.rb', line 5

def create_class(name, parent)
  klass = Class.new(parent)
  Object.const_set(name, klass)
  klass
end

#prefix_keys(attrs, prefix) ⇒ Object



38
39
40
# File 'lib/coco/test_helpers.rb', line 38

def prefix_keys(attrs, prefix)
  attrs.transform_keys! { [prefix, _1].map(&:to_s).join("-").tr("_", "-") }
end