# frozen_string_literal: true
require 'test_helper'

# *_with_other answers expect a hash response:
#   with_other: { other: 'TEXT-FIELD-VALUE', options: ['selected', 'answer', 'values'] }
class AnswerFormatValidatorTest < ActiveSupport::TestCase
  test "checkbox_other should PASS with populated array" do
    obj = AnswerValidatable.new('checkbox_other')
    obj.answer = { other: nil, options: ['some', 'selections', 'not-other'] }

    assert obj.valid?
    assert obj.errors.messages.empty?
  end

  test "checkbox_other should PASS with other and value" do
    obj = AnswerValidatable.new('checkbox_other')
    obj.answer = { other: 'some random user input', options: ['other', 'another option'] }

    assert obj.valid?
    assert obj.errors.messages.empty?
  end

  test "checkbox_other should FAIL with nil" do
    obj = AnswerValidatable.new('checkbox_other')
    obj.answer = nil

    refute obj.valid?
    assert_match(/select.*answer/, obj.errors.messages[:answer][0])
  end

  test "checkbox_other should FAIL with nil options" do
    obj = AnswerValidatable.new('checkbox_other')
    obj.answer = { other: '', options: nil }

    refute obj.valid?
    assert_match(/select.*answer/, obj.errors.messages[:answer][0])
  end

  test "checkbox_other should FAIL with empty string" do
    obj = AnswerValidatable.new('checkbox_other')
    obj.answer = { other: '', options: [''] }

    refute obj.valid?
    assert_match(/select.*answer/, obj.errors.messages[:answer][0])
  end

  test "checkbox_other should FAIL with other selected and no value" do
    obj = AnswerValidatable.new('checkbox_other')
    obj.answer = { other: '', options: %w(other some more selections) }

    refute obj.valid?
    assert_match(/select.*answer/, obj.errors.messages[:answer][0])
  end

  test "checkbox_other should FAIL with array of empty strings" do
    obj = AnswerValidatable.new('checkbox_other')
    obj.answer = { other: 'This is an unselected value', options: ["", "", "  "] }

    refute obj.valid?
    assert_match(/select.*answer/, obj.errors.messages[:answer][0])
  end
end
