0

我想为包含两个属性的关系模型创建一个工厂,followed_idfollower_id我不知道该怎么做,这是我的工厂文件:

FactoryGirl.define do

  factory :user do
    sequence(:name)  { |n| "Person #{n}" }
    sequence(:email) { |n| "person_#{n}@example.com"}
    password "foobar"
    password_confirmation "foobar"
  end

  factory :relationship do
    # i need something like this
    # followed_id a_user.id
    # follower_id another_user.id
  end

end

更新

我想用这个关系工厂做的是测试如果我摧毁一个用户,他所有的关系也会被摧毁,这是我的测试:

describe "relationships associations" do

let!(:relationship) { FactoryGirl.create(:relationship) }
it "should destroy associated relationships" do
  relationships = @user.relationships.to_a
  @user.destroy
  expect(relationships).not_to be_empty
  relationships.each do |relationship|
    expect(Relationships.where(id: relationship.id)).to be_empty
  end
end

结尾

4

3 回答 3

0

利用association

  factory :relationship do |r| # 'r' is how you call relationship in the block
    ...
    r.association :followed #relationship is associated with followed user 
    #(i'm not sure how your application is set up, 
    #so you'll have to do this as best makes sense.  
    #is followed an attribute of user?  
    #then it would look like `r.association :user`
    f.association :follower #same here
  end
于 2013-09-20T14:35:04.883 回答
0

根据我的经验,测试中很少需要这种“关系”工厂。相反,经常使用“user_with_followers”和“user_following_some_ones”。

factory :user do
  sequence(:name)  { |n| "Person #{n}" }
  sequence(:email) { |n| "person_#{n}@example.com"}
  password "foobar"
  password_confirmation "foobar"

  factory :user_with_followers do
    ignore do
      followers_count 5
    end

    after_create do |user, evaluator|
      followers = FactoryGirl.create_list(:user, evaluator.followers_count)
      followers.each do |follower|
        follower.follow(user) # Suppose you have a "follow()" method in User
      end
  end

  factory :user_following_some_ones do
    # Do the similar
  end
end

# Use
FactoryGirl.create :user_with_followers
于 2013-09-20T14:59:38.800 回答
0

在较新版本的 FactoryGirl 中,您应该能够做到这一点:

factory :relationship do
  association :followed, :factory => :user
  association :follower, :factory => :user
end

这两association行中的每一行所做的是设置一个用户实例(使用您的:user工厂),然后分配给当前关系实例的followedor follower

请注意,除非关联名称和工厂名称相同,否则您需要指定工厂。

更新:

创建关系时,请指定:followed:follower(以适用于您的为准)。否则,它会为每个用户创建新的用户记录并使用它们。

FactoryGirl.create(:relationship, :followed => @user)
于 2013-09-21T12:02:53.213 回答