2009-12-25 66 views
2

使用嵌套模型的2.3.x + rails特性,我想我需要訪問表單構建器實例以正確指定渲染嵌套模型的部分。從復表單的示例拉動:在rails中測試(rspec)嵌套模型partials 2.3+

例如,下面是創建並傳遞表單生成器到嵌套模型渲染視圖的包圍形式:

<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> 

部分的任務是:

<%= 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> 

當我試圖規範中的一個部分這個樣子,我試着做趕上表單生成器作爲一個實例VAR:

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

這就提出了對使用的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' 

這樣的錯誤,什麼是正確的做法: 1)得到這樣一個規格例如FormBuilder? 2)spec嵌套模型和它們的視圖形式?

這對於正確的名字生成很重要。

+0

你應該接受pr0d1r2的回答,對我來說真是棒極了。 – 2010-07-20 18:56:05

回答

3

解決辦法是:

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