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?