Search code examples
rspecrspec-rails

how to test my form helper


I have written a rails form helper but I can't figure out how to write a test for it. Can anyone help? Here's the helper code.

module FormHelper
  def dropdown(form, obj_symbol, options, selected_value)
    form.select obj_symbol, options_for_select(options.collect { |s| [s[0].titleize, s[0]] }, selected: selected_value), {}, {:class => "dropdown"}
  end

  def nullable_bool_dropdown(form, obj_symbol, empty_value, selected_value)
    form.select(obj_symbol, options_for_select([["Yes", true], ["No", false]], selected: selected_value), {:include_blank => empty_value}, {:class => "dropdown"})
  end
end

And here's where I'm at with the test so far... just not sure how to finish it.

require "rails_helper"

describe FormHelper do
  describe "#dropdown" do
    it "returns dropdown html with class dropdown" do

      form = double("form_for")
      allow(form).to receive(:select) {nil}

      dropdown(form, :status, {"value1" => 0, "value2" => 1}, "1")

      expect(form).to receive(:select).with(:status)
    end
  end
end

Basically, for the dropdown function, I want to test that titleize was called on all the options, that the selected value was set correctly and that the class of dropdown was applied to the select tag.


Solution

  • The key is expect_any_instance_of(ActionView::Helpers::FormOptionsHelper).to receive(:options_for_select)

    You can read more about it here: Rspec expect_any_instance_of

    Full Solution:

    require 'rails_helper'
    
    RSpec.describe FormHelper, :type => :helper do
      it 'titleizes the options and sets the class' do
        options = "<option />"
    
        expect_any_instance_of(ActionView::Helpers::FormOptionsHelper).to receive(:options_for_select).with([["Value1", "value1"]], {:selected => "1"}).and_return options
    
        form_for = double("form_for")
        expect(form_for).to receive(:select).with(:status, options, {}, {:class => "dropdown"})
    
        helper.dropdown(form_for, :status, {"value1" => 0}, "1")
      end
    end