我刚刚打开 Factory_Girl 并试图弄清楚如何构建依赖工厂,由于新版本的原因,大多数问题似乎已经过时。
我正在使用关联,但除了创建关联对象之外,该对象似乎与主对象无关或不相关
基本上这就是我所拥有的
factory :computer do
serial_no "12345"
end
factory :allocation do
association :computer_id, factory: :computer
end
分配属于_to 计算机和计算机有_many 分配基本上分配是计算机移动或诸如此类的任何时间的记录。
我不确定自己做错了什么,但每次运行时,分配的computer_id 都是“1”,但计算机的ID 是随机的(通常是0-20 之间的数字),然后我的测试失败因为它找不到合适的计算机对象。
编辑:好像还不够混乱,实际的类名是Assignment,我试图简单地说。这是所涉及的实际代码,实际代码没有问题,因为 computer_id 和 user_id 在创建期间作为参数传递给 create 方法。
describe "GET index" do
it "assigns assignments as @assignment" do
Assignment.any_instance.stubs(:valid?).returns(true)
assignment = FactoryGirl.create :associated_assignment
get :index, {}, valid_session
assigns(:assignments).should eq([assignment])
end
end
涉及的工厂有
factory :user do
fname "John"
lname "Smith"
uname "jsmith"
position "placeholder"
end
factory :computer do
asset_tag "12345"
computer_name "comp1"
make "dell"
model "E6400"
serial_no "abc123"
end
factory :associated_assignment, class: Assignment do
association :user_id, factory: :user
association :computer_id, factory: :computer
assign_date '11-11-2008'
end
控制器是:
def index
@assignments = []
@computers = Computer.all
Computer.all.each do |asset|
@assignments << Assignment.where(:computer_id => asset.id).order("assign_date ASC").last
end
respond_to do |format|
format.html # index.html.erb
format.json { render json: @assignments }
format.xls { send_data @assignments.to_xls }
end
目前我正在运行这个替代测试来检查我的身份证:
describe "GET index" do
it "assigns assignments as @assignment" do
Assignment.any_instance.stubs(:valid?).returns(true)
assignment = FactoryGirl.create :associated_assignment
get :index, {}, valid_session
assigns(:computers).should eq([assignment])
end
end
这会返回以下内容,其中计算机的 ID 是随机的,但分配的 computer_id 始终为 1。
Failure/Error: assigns(:computers).should eq([assignment])
expected: [#<Assignment id: 12, user_id: 1, computer_id: 1, assign_date: "2008-11-11", created_at: "2012-09-10 23:59:48", updated_at: "2012-09-10 23:59:48">]
got: [#<Computer id: 14, serial_no: "abc123", asset_tag: 12345, computer_name: "comp1", make: "dell", model: "E6400", created_at: "2012-09-10 23:59:48", updated_at: "2012-09-10 23:59:48">]