使用具有关联的Factory时删除关联

时间:2013-10-26 21:06:40

标签: ruby-on-rails factory-bot

我有一个简单的:item工厂,其嵌套附件工作正常。

FactoryGirl.define do
  factory :item do
    before_create do |item|
      item.attachments << FactoryGirl.build(:attachment, attachable: item)
    end
  end
end

我想查看以下内容

it "is invalid without a photo" do 
  FactoryGirl.create(:item).should_not be_valid
end

如何在调用现有:item工厂时删除附件?

2 个答案:

答案 0 :(得分:1)

您可能希望有两个版本的项目工厂。一个不创建关联附件,一个不创建关联附件。这将使您拥有其他地方的项目工厂,而不依赖于附件。

FactoryGirl.define do
  factory :item
end

FactoryGirl.define do
  factory :item_with_attachments, :parent => :item do
    before_create do |item|
      item.attachments << FactoryGirl.build(:attachment, attachable: item)
    end
  end
end

另一种选择是在测试其有效性之前远程调用附件:

it "is invalid without a photo" do 
  item = FactoryGirl.create(:item)
  item.attachments.destroy_all
  item.should_not be_valid
end

答案 1 :(得分:1)

使用traits

FactoryGirl.define do
  factory :item do
    # default vals
  end

  trait :with_attachments do
    attachments { |item| FactoryGirl.build_list(:attachment, 1, attachable: item) }
  end
end

使用

FactoryGirl.create(:item, :with_attachments)
相关问题