Factory_Girl解释使用has_many

时间:2014-10-15 09:48:18

标签: ruby-on-rails ruby ruby-on-rails-4 rspec factory-bot

我想知道是否有人可以使用has_many解释以下工厂的评估者部分,我想我有一个理解,但我不确定我是否完全理解我的图像在哪里,所以我可以运行自定义验证方法对他们稍后在rspec测试中

FactoryGirl.define do
 factory :animal, class: Animal do
  name 'test'

   ignore do
    images_count 1
   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

所以如果我运行这个命令

animal = FactoryGirl.create(:animal, images_count: 4)
ap(animal)

 :id => 95,
 :animal_type => nil,
 :name => nil,
 :description => nil,
 :age => nil,
 :size => nil,
 :gender => nil,
 :spay_neuter => nil,
 :chipped => nil,
 :child_friendly => nil,
 :reference => nil,
 :dog_breed_id => nil,
 :user_id => nil,
 :created_at => Wed, 15 Oct 2014 08:56:56 UTC +00:00,
 :updated_at => Wed, 15 Oct 2014 08:56:56 UTC +00:00,
 :cat_breed_id => nil
}
# Not worried about nil entries as didn't pass anything to populate them

这将创建我的动物对象,然后它将创建4个动物:animal_image,但是当我尝试使用我创建的动物对象创建我的animal_images时,图像不存在

animal_image = AnimalImage.create(animal: animal)
ap(animal_image)

:id => nil,
:animal_id => 96,
:image => #<AnimalImageUploader:0x00000002e00478 @model=#<AnimalImage id: nil, animal_id: 96, image: nil, created_at: nil, updated_at: nil>, @mounted_as=:image>,
:created_at => nil,
:updated_at => nil
}

你可以看到id在那里,但不是我的图像

有没有人对我做错什么有任何想法?

另外根据评论,我检查了错误

@base=#<AnimalImage id: nil, animal_id: 96, image: nil, created_at: nil, updated_at: nil>, @messages={:base=>["Please add an image"]}>

这是我的AnimalImage设置

class AnimalImage < ActiveRecord::Base
  mount_uploader :image, AnimalImageUploader
  belongs_to :animal

  validate :limit_num_of_images
  validate :image_size_validation, :if => "image?"

  def limit_num_of_images
   if image.size < 1
     errors.add(:base, "Please add an image")
   end
  end

  def image_size_validation
    if image.size > 1.megabytes
     errors.add(:base, "Image's should be less than 1MB")
    end
 end    
end

由于

1 个答案:

答案 0 :(得分:1)

使用create_list时,FactoryGirl将为您构建关联对象。

只需创建一个新动物:

animal = FactoryGirl.create(:animal)

然后迭代其图像:

animal.animal_images

默认情况下,您应该有5张图片(在ignore属性中指定)。你可以像这样控制图像的数量:

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