我想为Relationship模型创建一个工厂,它包含两个属性followed_id
和follower_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
端
答案 0 :(得分:0)
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
答案 1 :(得分: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
答案 2 :(得分:0)
在最近的FactoryGirl版本中,您应该可以这样做:
factory :relationship do
association :followed, :factory => :user
association :follower, :factory => :user
end
这两条association
行中的每一行都设置了一个用户实例(使用:user
工厂),然后分配给当前的followed
或follower
关系实例。
请注意,除非关联名称和工厂名称相同,否则您需要指定工厂。
<强>更新强>
创建关系时,请指定:followed
或:follower
(以适用者为准)。否则,它会为每个用户创建新的用户记录并使用它们。
FactoryGirl.create(:relationship, :followed => @user)