Reputation: 10208
I have the following model:
class ProfileAssignment < ActiveRecord::Base
belongs_to :profile
belongs_to :destination_profile, :class_name => "Profile"
attr_accessible :profile_id, :destination_profile_id
end
I want to create a factory for this simple class.
This is what I have:
THis is my Profile factory:
FactoryGirl.define do
factory :profile do
name "MyString"
end
factory :destination_profile do
name "Other profile"
end
end
And this is my ProfileAssignment factory
FactoryGirl.define do
factory :profile_assignment do
profile
association :destination_profile, factory: :destination_profile
end
end
But I get the following error:
Failure/Error: expect(FactoryGirl.create(:profile_assignment).valid?).to be_true
NameError:
uninitialized constant DestinationProfile
What am I doing wrong?
Upvotes: 1
Views: 171
Reputation: 29369
If you are defining factory destination_profile
for Profile class, then you will have to mention the class explicitly.
Factory girl tries to initialize the class based on the factory name. So if you name your factory as destination_profile, it will look for a class named DestinationProfile. Provide class information to the destination_profile factory
FactoryGirl.define do
factory :profile do
name "MyString"
end
factory :destination_profile, :class => Profile do
name "Other profile"
end
end
Also you don't have to specify the factory explicitly, if your association name matches the factory name
FactoryGirl.define do
factory :profile_assignment do
profile
association :destination_profile
end
end
Have a loot at rspec traits if you want multiple factories for the same class.
Upvotes: 1