更新:
下面的代码在我的环境中运行良好(Rails3.2.2,ruby 1.8.7)
# parent.rb
class Parent < ActiveRecord::Base
has_one :child
validates :child, :presence => true
end
# child.rb
class Child < ActiveRecord::Base
belongs_to :parent
validate :parent, :presence => true
end
# parent_test.rb
require 'test_helper'
class ParentTest < ActiveSupport::TestCase
test "should be saved" do
parent = Parent.new(:name => "111")
child = Child.new(:name => "222", :parent => parent)
parent.child = child
parent.save!
puts "after saved, parent: #{parent.inspect}"
puts "after saved, child: #{child.inspect}"
assert parent.id > 0
assert child.id > 0
end
end
运行此测试并得到:
Started
after saved, parent: #<Parent id: 980190963, name: "111", created_at: "2012-04-05 23:19:31", updated_at: "2012-04-05 23:19:31">
after saved, child: #<Child id: 980190963, name: "222", parent_id: 980190963, created_at: "2012-04-05 23:19:31", updated_at: "2012-04-05 23:19:31">
.
Finished in 0.172716 seconds.
1 tests, 2 assertions, 0 failures, 0 errors
以前的答案 =================
尝试分别初始化它们,然后添加关联,最后保存它们。
parent = FactoryGirl.build(:parent)
child = FactoryGirl.build(:child, :parent => parent)
parent.child = child
parent.save
child.save # seems this line of code is redundant? I am not sure.
有关“构建,创建”的更多详细信息,请参见其官网:https ://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md