Skip to content

Instantly share code, notes, and snippets.

@everton
Last active August 10, 2022 12:51
Show Gist options
  • Save everton/a1f5bbef553d88df7892e7bda3d3d0db to your computer and use it in GitHub Desktop.
Save everton/a1f5bbef553d88df7892e7bda3d3d0db to your computer and use it in GitHub Desktop.
module FormTestHelper
def assert_form(action, options = {}, &block)
method = options.delete(:method) || :post
if method == :put || method == :patch || method == :delete
virtual_method, method = method, :post
test_body = -> (*args) {
assert_select "input[type='hidden'][name='_method']",
value: virtual_method
block.call(*args) if block
}
elsif method == :post
test_body = -> (*args) {
assert_select "input[name='_method']", count: 0
block.call(*args) if block
}
else
test_body ||= block
end
assert_select 'form[action=?][method=?]', action, method.to_s, options, &test_body
end
def assert_input(name, value = nil, type: :text, label: nil, labels: nil, with_errors: false, **options)
options[:type ] = type
options[:name ] = name
options[:value] = value if value
selector = with_errors ? '.field_with_errors input' : 'input'
selector += options.map { |k, v| "[#{k}=\"#{v}\"]" }.join
assert_select selector
if labels
labels.each do |_id, label|
assert_select 'label[for=?]', _id.to_s, text: label
end
elsif label
_id = name.tr('[', '_').tr(']', '')
assert_select 'label[for=?]', _id, text: label
end
end
def assert_input_select(name, label: nil, options: nil, options_count: nil, with_errors: false, **other_options)
selector = with_errors ? ".field_with_errors " : ""
selector += "select[name=?]"
assert_select selector, name.to_s, **other_options do |node|
if options
Array(options).each do |option|
value, text = option
if text
assert_option value, text
else
assert_option value
end
end
end
if options_count
assert_equal options_count, node.css("option").count,
"Wrong number of options"
end
yield(node) if block_given?
end
_id = name.tr('[', '_').tr(']', '')
assert_select 'label[for=?]', _id, text: label if label
end
def assert_option(value, text = value.to_s)
assert_select('option[value=?]', value.to_s, text: text)
end
def assert_selected_option(value, text = value.to_s)
assert_select('option[selected=selected][value=?]', value.to_s, text: text)
end
def assert_submit_buttons(*button_texts)
button_texts.each do |button_text|
assert_select "input[type='submit'][name='commit'][value=?]", button_text
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment