Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/54.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何创建具有多个关联的有效工厂_Ruby On Rails_Factory Bot - Fatal编程技术网

Ruby on rails 如何创建具有多个关联的有效工厂

Ruby on rails 如何创建具有多个关联的有效工厂,ruby-on-rails,factory-bot,Ruby On Rails,Factory Bot,我一直在努力让这项工作,看看,并在这里看了一些例子。无论我尝试什么,我都会出错 我正在寻找一个工作示例,以了解测试的结构;我使用的是Factory Girl 4.4.1和Rspec 3 我创建有效对象的唯一方法是这样做,但这不是构建对象的正确方法,因为我仍然希望先对动物模型进行验证,然后再对动物图像进行验证 FactoryGirl.define do factory :animal_image do animal_id 1 image { File.open("#{Rails.r

我一直在努力让这项工作,看看,并在这里看了一些例子。无论我尝试什么,我都会出错

我正在寻找一个工作示例,以了解测试的结构;我使用的是Factory Girl 4.4.1和Rspec 3

我创建有效对象的唯一方法是这样做,但这不是构建对象的正确方法,因为我仍然希望先对动物模型进行验证,然后再对动物图像进行验证

FactoryGirl.define do
  factory :animal_image do
   animal_id 1
   image { File.open("#{Rails.root}/spec/fixtures/yp2.jpg") }
 end 
end

file = FactoryGirl.create(:animal_image)
#<AnimalImage id: 101, animal_id: 1, image: "yp2.jpg", created_at: "2014-10-14 10:08:55", updated_at: "2014-10-14 10:08:55">
FactoryGirl.define do
工厂:动物图片怎么办
动物识别号1
图像{File.open(“#{Rails.root}/spec/fixtures/yp2.jpg”)}
结束
结束
file=FactoryGirl.create(:动物图片)
#
我的模型

class Animal < ActiveRecord::Base
  has_many :animal_images, dependent: :destroy
end

class AnimalImage < ActiveRecord::Base
  belongs_to :animal
end
class Animal
试试这个:

FactoryGirl.define do
  factory :animal do

    ignore do
      images_count 5
    end

    after(:create) do |animal, evaluator|
      create_list(:animal_image, evaluator.images_count, animal: animal)
    end

  end 
end

FactoryGirl.define do
  factory :animal_image do

    image { File.open("#{Rails.root}/spec/fixtures/yp2.jpg") }

  end 
end

a = FactoryGirl.create(:animal)
a.animal_images.count
=> 5

a = FactoryGirl.create(:animal, images_count: 1)
a.animal_images.count
=> 1

更多信息

谢谢,我尝试了官方的factory\u girl文档,他们有
瞬态do posts\u count 5 end
,在您的示例中,我们忽略了这一点?有什么区别吗?他们必须在
transient
中重命名
ignore
,但想法是一样的。在构建类实例时,它是一个被忽略的属性。。我的尝试在images\u count上失败了。欢迎您,编辑了transient thing,谢谢您,我也学到了一些东西。啊,对于任何混淆,很抱歉,
ignore
起作用,
transient
抛出了未定义的方法“images\u count”,所以从我所知,使用ignore更好