require 'rails_helper'

describe ApplicationController do

  # sanitization is a protected method, so we make a local anon version
  # in order to call it as a "public" method for the tests
  controller do
    def sanitize_params!
      super
    end
  end

  context 'sanitize_params!' do

    before(:each) do
      # set/reset params hash before each test
      controller.params = ActionController::Parameters.new({
        top_number: 24,
        top_name_with_post_whitespace: "name\t ",
        top_name_with_pre_whitespace: "\t name",
        top_name_with_pre_and_post_whitespace: " \tname \t",
        top_name_with_middle_space: "na me",
        top_name_with_pre_middle_post_space: "\t na \tme \t",
        child_hash: {
          child_number: 24,
          child_name_with_post_whitespace: "name\t ",
          child_name_with_pre_whitespace: "\t name",
          child_name_with_pre_and_post_whitespace: " \tname \t",
          child_name_with_middle_space: "na me",
          child_name_with_pre_middle_post_space: "\t na \tme \t"
        }
      })
    end

    it "trims pre and post whitespace from strings when present" do

      controller.sanitize_params!

      expect(controller.params[:child_hash]).to_not eq(nil)

      expect(controller.params[:top_number]).to eq(24)

      expect(controller.params[:top_name_with_post_whitespace]).to eq("name")
      expect(controller.params[:top_name_with_pre_whitespace]).to eq("name")
      expect(controller.params[:top_name_with_pre_and_post_whitespace]).to eq("name")
      expect(controller.params[:top_name_with_pre_middle_post_space]).to eq("na \tme")

      expect(controller.params[:child_hash][:child_name_with_post_whitespace]).to eq("name")
      expect(controller.params[:child_hash][:child_name_with_pre_whitespace]).to eq("name")
      expect(controller.params[:child_hash][:child_name_with_pre_and_post_whitespace]).to eq("name")
      expect(controller.params[:child_hash][:child_name_with_pre_middle_post_space]).to eq("na \tme")

    end

    it "returns the original string when unchanged" do

      controller.sanitize_params!

      expect(controller.params[:child_hash][:child_number]).to eq(24)

      expect(controller.params[:top_name_with_middle_space]).to eq("na me")

      expect(controller.params[:child_hash][:child_name_with_middle_space]).to eq("na me")

    end

  end

end
