以下方法适当地传递测试:
def associate_grid_location
devices.each do |device|
if device.grid_location and grid_location_id.nil?
update_attribute(:grid_location_name,device.grid_location.grid_name)
update_attribute(:grid_location_id,device.grid_location_id)
break
end
end
end
但是,如果我在调用此方法时运行相同的测试逻辑,则无法更新每个机柜的grid_location_name和grid_location_id:
def self.associate_grid_locations
Cabinet.all.each do |cabinet|
cabinet.associate_grid_location
end
end
请说明为什么会失败。
通过考试:
test "Cabinet associate grid location from device where device has grid location" do
@cabinet = cabinets(:one)
@cabinet.grid_location_id = nil
@device = devices(:one)
@grid_location = grid_locations(:one)
@grid_location.grid_name = "test location"
@device.grid_location = @grid_location
@cabinet.devices << @device
@cabinet.associate_grid_location
assert_equal @grid_location.grid_name, @cabinet.grid_location_name, "Failed: Did not update cabinet grid location"
assert_equal @device.grid_location.id, @cabinet.grid_location_id, "Failed: Did not update cabinet grid location"
end
测试失败:
test "Cabinet associate grid location from device where device has grid location (Called on Cabinet)" do
@cabinet = cabinets(:one)
@cabinet.grid_location_id = nil
@device = devices(:one)
@grid_location = grid_locations(:one)
@grid_location.grid_name = "test location"
@device.grid_location = @grid_location
@cabinet.devices << @device
Cabinet.associate_grid_locations
assert_equal @grid_location.grid_name, @cabinet.grid_location_name, "Failed: Did not update cabinet grid location"
assert_equal @device.grid_location.id, @cabinet.grid_location_id, "Failed: Did not update cabinet grid location"
end
谢谢。
答案 0 :(得分:0)
Cabinet.associate_grid_locations
调用Cabinet.all
,它实例化新对象(除非您启用了身份映射),这些对象未链接到您在测试中实例化的对象。假设没有其他错误,在#reload
上调用@cabinet
会使测试通过。