Ruby on rails 如何使用Rails上具有多个关联的模型生成FactoryGirl关联?
我正在阅读Michael Hartl的教程,但是使用RSpec而不是minitest测试来学习RSpec。当他创建关系测试时,我来到了 型号: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
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