views:

366

answers:

1

With the 2.3.x+ rails feature of nested models, I think I need to have access to a form builder instance to properly spec partials for rendering the nested models. Pulling from the complex-forms-examples:

For example, here is an enclosing form that creates and passes the form builder to the nested model rendering view:

<div class="children_fields tasks" id="<%= dom_id(f.object) %>_tasks"  
   data-context="<%= f.object_name %>">
  <% f.fields_for :tasks do |task_form| %>
    <%= render :partial => 'task', :locals => { :f => task_form } %>
  <% end %>    
</div>

The task partial is:

<%= f.label :name, "Task" %>
<%= f.text_field :name %>
<%= remove_child_link "remove", '#', f %>
<div class="children_fields assignments" id="<%= dom_id(f.object) %>_assignments"  
     data-context="<%= f.object_name %>">
  <% f.fields_for :assignments do |assignment_form| %>
    <%= render :partial => 'assignment', :locals => { :f => assignment_form } %>
  <% end %>
</div>

When I try to spec a partial like this, I tried to catch the form builder as an instance var by doing:

before(:each) do
  ... # setup for target object
  form_for [:foo, :bar, @project] do |f|
    @f = f
  end
end

This raises an error on the use of form_for

undefined method `polymorphic_path' for #<Spec::Rails::Example::ViewExampleGroup::Subclass_1:0x2cfeafc>
/Users/adamaig/.rvm/gems/ruby/1.8.7/gems/actionpack-2.3.5/lib/action_controller/test_process.rb:511:in `method_missing'
/Users/adamaig/.rvm/gems/ruby/1.8.7/gems/actionpack-2.3.5/lib/action_view/helpers/form_helper.rb:298:in `apply_form_for_options!'
/Users/adamaig/.rvm/gems/ruby/1.8.7/gems/actionpack-2.3.5/lib/action_view/helpers/form_helper.rb:272:in `form_for'

So, What is the right way to: 1) get a FormBuilder instance for specs like this? 2) spec nested models and their view forms?

This matters for the proper name generation.

+1  A: 

Solution is:

describe 'tasks/_form' do
  attr_accessor :output_buffer

  before do
    task = mock_model(Task, :mumbo_jumbo => 'foo bar')
    @output_buffer = ''
    form_for(task, :url => task_path(task)) do |f|
      @f = f
    end
  end

  it 'should have input mumbo_jumbo' do
    render_partial_with_locals
    response.should have_tag('input[name=?]', 'task[mumbo_jumbo]')
  end

  private

    def render_partial_with_locals
      render :partial => 'tasks/form', :locals => {:f => @f}
    end

    def protect_against_forgery?
      false
    end
end