¿Cómo se crean asociaciones de RoR Factory con accept_nested_attributes_for?
-
06-07-2019 - |
Pregunta
Como señala Anton (¡gracias Anton!) mi problema es el almacenamiento en caché de asociación en las pruebas y parece que creé correctamente el atributo nested_attribute en la fábrica. La sintaxis correcta es:
Factory.define :job do |f|
...
f.vehicles_attributes [{:vin => "1", :model => "ford", :make => "escort"},{:vin => "1", :model => "ford", :make => "escort" }]
end
Estoy usando accept_nested__attributes_for
en mi modelo de trabajo y estoy tratando de migrar a una chica de fábrica después de casi perder mis canicas '' buceo con accesorios '' Cada vez que cambio el modelo.
Publiqué un montón de código a continuación, pero mi pregunta es sencilla:
¿Cómo utilizo las fábricas para crear atributos_anclados?
Puedo crear una instancia de Job usando el código a continuación, pero no puedo crear crear vehículos en las pruebas de mi unidad. Sin los f.vehicles_attributes ...
mis pruebas de trabajo no validan.
Las pruebas de mi unidad producen los siguientes resultados:
test "factory" do
job = Factory(:job)
assert(job.valid?) # => true
assert(job.vehicles.first.valid?) # => true
vehicle = Factory(:vehicle)
assert(vehicle.job.vehicles.size == 1) # => true
assert_equal(vehicle.job.vehicles.first.vin, "2") # => FALSE. <"1"> expected but was <"2">
end
Factory.define :job do |f|
...
f.vehicles_attributes [:vin => "1", :model => "ford", :make => "escort" ]
end
Factory.define :vehicle do |f|
f.vin "2"
f.model "ford"
f.make "escort"
f.association :job
end
class Job < ActiveRecord::Base
has_many :vehicles, :dependent => :destroy
validate :job_must_have_at_least_one_vehicle
accepts_nested_attributes_for :vehicles, :allow_destroy => :true, :reject_if => proc { |vehicle_attributes| Job.insufficient_vehicle_input?(vehicle_attributes) }
def job_must_have_at_least_one_vehicle
errors.add(:vehicles, "need to be added") if self.vehicles.empty?
end
def self.insufficient_vehicle_input?(vehicle_attributes)
vehicle_property_keys = vehicle_attributes.keys
vehicle_property_keys.delete('_delete')
vehicle_property_keys.delete('is_operational')
vehicle_property_keys.delete('has_keys')
vehicle_property_keys.each do |attribute_to_validate|
if(!vehicle_attributes[attribute_to_validate].nil? && !vehicle_attributes[attribute_to_validate].empty?)
return false
end
end
return true
end
end
Solución
Se trata de almacenamiento en caché de asociación .
Así es como funciona:
1. Factory (: vehicle)
crea el objeto vehicle
y crea el registro job
2. Después de eso, llena vehicle.job_id
y lo guarda
Pero vehicle.job
señala un objeto job
del paso 1.
Entonces, todo lo que necesita es volver a cargar trabajo
:
vehicle = Factory(:vehicle)
vehicle.job.reload.vehicles.size # => 2