1

我刚刚开始尝试 Rails 测试。我很难开始。

我的第一个测试需要一个用户,这是我在 FactoryGirl 中创建的。但是我的模型验证了邀请的存在。

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

如何使用 FactoryGirl 生成受邀用户?

我尝试了几种方法,但没有设置关联。似乎最有可能起作用的是:

factory :invitation do
  token "MyInvitationToken"
  recipient_email "test@example.com"

  factory :invited_user do
    association :user, :factory => :user
  end
end

factory :user do
  email "test@example.com"
end

这是失败的Validation failed: Invitation is required

与 FactoryGirl 建立这种关联的正确方法是什么?

对于奖励积分,我如何修改它以使 :invitation.recipient_email 是一个序列sequence(:recipient_email) { |n| "test#{n}@example.com" },并且该值在每次迭代时都会传递到被邀请用户的电子邮件列。

4

1 回答 1

1

您可以使用:

factory :user do
  email "test@example.com"
  f.association :invitation
end

或者

factory :user do
  email "test@example.com"

  after_build do |foo|
    user.invitations << Factory.build(:invitation)
  end
end
于 2012-04-21T05:04:18.423 回答