Reputation: 44066
I have this factory
FactoryGirl.define do
factory :user do
email { Faker::Internet.email }
first_name { Faker::Name.first_name }
last_name { Faker::Name.last_name }
password { 'TarXlrOPfaokNOzls2U8' }
end
end
Which worked great until I added the association validation
class User < ActiveRecord::Base
has_many :companies, :through => :positions
has_many :positions
validates_presence_of :company
How do I add to my factory to achieve this
I tried this
association :company, factory: :company, strategy: :build
But all my tests are failing with
undefined method `company=' for #<User:0x007fcd7c13c260>
any help would be appreciated
Upvotes: 0
Views: 177
Reputation: 1088
Have you tried simply?
FactoryGirl.define do
factory :user do
email { Faker::Internet.email }
first_name { Faker::Name.first_name }
last_name { Faker::Name.last_name }
password { 'TarXlrOPfaokNOzls2U8' }
companies { [Factory(:company, strategy: build)] }
end
end
Upvotes: 3
Reputation: 17480
You'll want a factory for company, user and position, than override the defaults as necessary:
factory :position do
user
company
end
factory :company do
#company stuff
end
user = create(:user)
company = create(:company)
postion = create(:position, user: user, company: company)
user.company.should eq company
Upvotes: 0
Reputation: 4515
If you want to have 1 company per user then you need to use belongs_to :company
in the User model instead of an has_many. If you really want to have many companies per user, see this answer.
Upvotes: 1