3

I have two factories for my Company and Employee models respectively. Employee is in a belongs_to relationship with Company. Here's my two factories:

factory :company do
  name "foo company"
end

factory :employee do
  company
  name 'Willy Bytes'      
end

There are some occasions where I need to traverse an array of data and populate new Employee records accordingly to test against different conditions in my specs. To illustrate, I'm using the following specs to test one of my inclusion validations:

it "should be valid if they like red blue or green" do
  ["red","blue","green"].each do |c|
    FactoryGirl.build(:employee, :favourite_colour => c).should be_valid
  end
end

it { FactoryGirl.build(:upload, :favourite_colour => "other").should_not be_valid }

However, I have a uniqueness constraint on the parent companies name field which yields an error when I attempt to build the record. Is there an intelligent way to resolve/avoid this problem? I run into these types of specs a lot and typically what I would do is define a single Company factory and assign that to each record in the loop, but it doesn't feel intuitive and results in a lot of repetition. Is a sequence the only other way around this?

4

3 回答 3

0

我在这里找到了我想要的东西:Find or create record through factory_girl Association

使用该方法覆盖默认的构建/新行为initialize_with似乎是要走的路:

factory :company do
 initialize_with { Company.find_or_create_by_name("Foo Company") }
end
于 2013-06-24T20:01:01.590 回答
0

您可以使用 factory_girl 的序列生成器。您的工厂将如下所示。

factory :company do
  sequence(:name) {|n| "company #{n}"}
end
于 2013-06-24T19:32:31.500 回答
0

一条线:

sequence(:name) { |n| "Company #{n}" }
于 2013-06-24T19:37:36.787 回答