如何与在 Rails 上具有多个关联的模型生成 FactoryGirl 关联?

How to generate FactoryGirl association with model having multiple associations on Rails?

我正在阅读 Michael Hartl 的教程,但使用 RSpec 而不是 minitest 测试来学习 RSpec。当他创建 Relationships 测试时,我来到了 last chapter

型号:

class User < ApplicationRecord
  has_many :microposts, dependent: :destroy
  has_many :active_relationships, class_name:  "Relationship",
                                  foreign_key: "follower_id",
                                  dependent:   :destroy
...

class Relationship < ApplicationRecord
  belongs_to :follower, class_name: "User"
  belongs_to :followed, class_name: "User"
end

这是他的最小版本(作品):

class RelationshipTest < ActiveSupport::TestCase

  def setup
    @relationship = Relationship.new(follower_id: users(:michael).id,
                                     followed_id: users(:archer).id)
  end
...

我正在尝试用 RSpec + FactoryGirl 重新创建它,但我无法正确关联关系。

这是我当前的模型测试:

//spec/models/relationship_spec.rb
let(:relationship) {FactoryGirl.create(:relationship)}

  it "should be valid" do
    expect(relationship).to be_valid
  end

首先我尝试硬编码我的关系工厂:

FactoryGirl.define do
  factory :relationship do
    follower_id 1
    followed_id 2
  end
end
// error  ActiveRecord::RecordInvalid: Validation failed: Follower must exist, Followed must exist

然后我尝试添加 user(我有另一个工厂 :user

FactoryGirl.define do
  factory :relationship do
    user
  end
end
// NoMethodError: undefined method `user=' for #<Relationship:0x007fa8b9194a10>

现在对其进行硬编码 let(:relationship) {Relationship.new(follower_id: 1, followed_id: 2)} 可行,但看起来不正确。我需要做什么才能生成 relationship 工厂?

您的硬编码 follower_idfollowed_id 值似乎会引发错误,因为这些用户仍然不存在。

工厂女郎的关系可以这样写:

FactoryGirl.define do
  factory :relationship do
    follower
    followed
  end
end

每当您调用 create(:relationship) FactoryGirl 都会为此新关系创建用户实例。