FactoryGirl Callbacks

时间:2015-12-14 14:11:24

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

我有以下协会,并且正在尝试实施一些工厂,这些工厂允许我使用has_manyhas_many_through关联进行完全测试

class Image < ActiveRecord::Base
  has_many :categories
end

class Category < ActiveRecord::Base
  belongs_to :image
  has_many :image_categories
  has_many :images, through: :image_categories
end

class ImageCategory < ActiveRecord::Base
  # Holds image_id and category_id to allow multiple categories to be saved per image, as opposed to storing an array of objects in one DB column
  belongs_to :image
  belongs_to :category
end

因此,对于ImageCategory,我认为当我保存Image对象时,image_idcategory_id会保存在ImageCategory表中?我还没有在我的申请中看到这种想法

因此,在创建工厂时,这是我目前所拥有的

FactoryGirl.define do
  factory :image do
    title 'Test Title'
    description 'Test Description'
    photo File.new("#{Rails.root}/spec/fixtures/louvre_under_2mb.jpg")

  factory :image_with_category, parent: :image do
    categories { build_list :category, 1 }
  end

  factory :image_no_title do
    title nil
  end

 factory :image_no_description do
   description nil
 end

 factory :image_no_category, parent: :image do 
   categories { build_list :category, 0 }
 end
end
 end 

我不明白build_list中category之后的整数值是多少?它是实例的数量吗?

此测试将通过

it 'is valid with an associated Category' do
  expect(FactoryGirl.build(:image_with_category)).to be_valid
end

然而这个会失败

it 'is invalid with no category' do
  @image = FactoryGirl.build(:image_no_category)
  @image.save
  expect(@image.errors[:category]).to eq(["Don't forget to add a Category"])
end

expected: ["Don't forget to add a Category"]
got: []

我在这里做错了什么?

由于

1 个答案:

答案 0 :(得分:1)

你是正确的build_list是用于构建实例的FactoryGirl助手。在第二次测试中,您没有任何错误,因为您根本没有任何验证。