如何测试我的表单助手

时间:2014-07-14 19:27:54

标签: rspec rspec-rails

我已经编写了一个rails form helper,但我无法弄清楚如何为它编写测试。有人可以帮忙吗?这是帮助代码。

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

到目前为止,这是我参加测试的地方......只是不确定如何完成它。

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

基本上,对于下拉函数,我想测试在所有选项上调用titleize,选择的值是否设置正确以及下拉类是否应用于select标记。

1 个答案:

答案 0 :(得分:1)

关键是expect_any_instance_of(ActionView::Helpers::FormOptionsHelper).to receive(:options_for_select)

您可以在此处详细了解:Rspec expect_any_instance_of

完整解决方案:

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