I have a category model. I am using ancestry gem to make it like a tree structure so that we can have sub categories. I have a simple factory for category that looks like this
factory :category do
sequence(:name) { |n| "Category #{n}"}
end
I have another model business which has a main_category and a sub_category. Here is my factory for the business
factory :business do
sequence(:name) { |n| "businnes#{n}"}
sequence(:email) { |n| "busixy#{n}@example.com"}
sequence(:website) { |n| "www.example#{n}.com"}
association(:main_sub_category)
main_category {Business.main_sub_category.parent}
end
What I am trying to do here is to assign main_sub_category of the business a new category which is a sub_category and to assign the parent of that category to main_category of the business.
To get this I created a new factory called sub_category
factory :category do
sequence(:name) { |n| “Category #{n}”}
factory :subcategory do |sub|
sub.parent factory :category
end
end
When I try the above code I get this error
Factory already registered: category (FactoryGirl::DuplicateDefinitionError)
I tried another way to do it
factory :category do
sequence(:name) { |n| "Category #{n}"}
factory :subcategory do |sub|
sub.parent {FactoryGirl.create(:category)}
end
end
This way it works but when I create a business object using the factory
@business = FactoryGirl.create :business
It gives me validation error
ActiveRecord::RecordInvalid: Validation failed: Name has already been taken
I have a uniqueness validation on category names.
Any has had this kind of a recursive factory issue kind help.
Thanks
Got it resolved, for some mysterious reason I don’t understand my test db had a already had a single entry for a category with name Category1 which was creating the issue, manually deleted that row using mysql console and everthing works now.
I still wonder why database wasn’t clear, since I never write to test db directly its the testcase that do it.. :S