我有 Pupil 模型。所以我可以保存和编辑学生。学生has_one 手机(和手机belongs_to pupil)和app通过嵌套属性用手机保存学生。一切都在浏览器中运行良好,但当我尝试测试更新 Pupil 模型时,我会遇到一些麻烦。
控制器:
class PupilsController < ApplicationController
...
def edit
@pupil = Pupil.find( params[:id] )
end
def update
pupil = Pupil.find( params[:id] )
if pupil.update_attributes( params[:pupil] )
redirect_to pupils_path
...
else
redirect_to edit_pupil_path
...
end
end
end
编辑页面查看:
<%= form_for @pupil, :html => {:class => "form-horizontal"} do |f| %>
<%= field_set_tag do %>
...
<div class="control-group">
<%= f.label :pupil_address_of_living, "Address of living", :class => "control-label" %>
<div class="controls">
<%= f.text_area :pupil_address_of_living, :rows => 3,
:placeholder => @everpresent_field_placeholder %>
</div>
</div>
<hr/>
<%= f.fields_for :pupil_phone do |pp| %>
<div class="control-group">
<%= pp.label :pupil_home_number, "Home phone", :class => "control-label" %>
<div class="controls">
<%= pp.text_field :pupil_home_number, :placeholder => @everpresent_field_placeholder %>
</div>
</div>
...
<% end %>
<%= f.submit "Change", :class => "btn btn-large btn-warning" %>
<% end %>
<% end %>
我的集成测试实际上失败了:
# encoding: UTF-8
require 'spec_helper'
describe "SchoolHeads" do
before(:each) do
@attr = {
:user_login => "iSchool_head",
:password => "foobar"
}
user = User.new( @attr )
user.user_role = "school_head"
user.save!
end
...
describe "Updating" do
describe "View" do
before(:each) do
@ipupil = Factory( :pupil, :pupil_phone => Factory( :pupil_phone ))
visit edit_pupil_path( :id => @ipupil.id )
end
it "should have values in forms" do
response.should have_selector("form") do |form|
...
form.should have_selector("input", :name => "pupil[pupil_phone_attributes][pupil_home_number]")
end
end
end
测试:中的错误
Failure/Error: form.should have_selector( "input",
expected following output to contain a <input name='pupil[pupil_phone_attributes][pupil_home_number]'/> tag:
<form accept-charset="UTF-8" action="/pupils/220" class="form-horizontal" id="edit_pupil_220" method="post">
<div style="margin:0;padding:0;display:inline">
<input name="utf8" type="hidden" value="✓"><input name="_method" type="hidden" value="put">
</div>
<fieldset>
...
<div class="control-group">
<label class="control-label" for="pupil_pupil_address_of_living">Address of living</label>
<div class="controls">
<textarea cols="40" id="pupil_pupil_address_of_living" name="pupil[pupil_address_of_living]" rows="3">Moscow</textarea>
</div>
</div>
<hr>
# Here i should have part of form with phones which is not rendering.
<input class="btn btn-large btn-warning" name="commit" type="submit" value="Change">
</fieldset>
</form>
我从未遇到过这样的奇怪问题。是bug还是什么?这是我的错吗?
答案 0 :(得分:0)
我解决了这个问题。非常感谢 pjumble 注意到这个问题。问题是工厂没有正确设置关系。所以我改变了代码:
before(:each) do
@ipupil = FactoryGirl.create( :pupil )
@attr_pupil_phones = { :pupil_home_number => "8903111111",
:pupil_mobile_number => "777-33-22" }
@ipupil.create_pupil_phone( @attr_pupil_phones )
...
end
现在可行。