Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/60.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何使用Rails上具有多个关联的模型生成FactoryGirl关联?_Ruby On Rails_Factory Bot - Fatal编程技术网

Ruby on rails 如何使用Rails上具有多个关联的模型生成FactoryGirl关联?

Ruby on rails 如何使用Rails上具有多个关联的模型生成FactoryGirl关联?,ruby-on-rails,factory-bot,Ruby On Rails,Factory Bot,我正在阅读Michael Hartl的教程,但是使用RSpec而不是minitest测试来学习RSpec。当他创建关系测试时,我来到了 型号: class User < ApplicationRecord has_many :microposts, dependent: :destroy has_many :active_relationships, class_name: "Relationship", for

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

型号:

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
首先,我尝试硬编码我的关系工厂:

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
工厂:关系如何
用户
结束
结束
//NoMethodError:的未定义方法“user=”#

现在硬编码它
let(:relationship){relationship.new(follower\u id:1,follower\u id:2)}
可以工作,但它看起来不正确。要生成
关系
工厂,我必须做些什么

您硬编码的
follower\u id
follower\u id
值似乎会产生错误,因为这些用户仍然不存在

对于factory girl中的关系,您可以这样写:

FactoryGirl.define do
  factory :relationship do
    follower
    followed
  end
end
无论何时调用
create(:relationship)
FactoryGirl都将为此新关系创建用户实例

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
FactoryGirl.define do
  factory :relationship do
    user
  end
end
// NoMethodError: undefined method `user=' for #<Relationship:0x007fa8b9194a10>
FactoryGirl.define do
  factory :relationship do
    follower
    followed
  end
end