Reputation: 12663
I'm just beginning to experiment with Rails tests. I'm having trouble getting started.
My first tests require a User, which I'm creating within FactoryGirl. But my model validates presence of an invitation.
class User
has_many :sent_invitations, :class_name => 'Invitation', :foreign_key => 'sender_id'
belongs_to :invitation
validates_presence_of :invitation_id
end
class Invitation
belongs_to :sender, :class_name => 'User'
has_one :recipient, :class_name => 'User'
end
How do I generate an invited user using FactoryGirl?
I've tried a few approaches, but the association is not being set. The one that seems most likely to work is something like:
factory :invitation do
token "MyInvitationToken"
recipient_email "[email protected]"
factory :invited_user do
association :user, :factory => :user
end
end
factory :user do
email "[email protected]"
end
This is failing with Validation failed: Invitation is required
.
What is the correct way to establish this association with FactoryGirl?
For bonus points, how can I modify this so the :invitation.recipient_email is a sequence sequence(:recipient_email) { |n| "test#{n}@example.com" }
, and that this value gets passed to the invited_user's email column for each iteration.
Upvotes: 1
Views: 1153
Reputation: 151
you can use:
factory :user do
email "[email protected]"
f.association :invitation
end
OR
factory :user do
email "[email protected]"
after_build do |foo|
user.invitations << Factory.build(:invitation)
end
end
Upvotes: 1