0
我正在通过Michael Hartl的教程,但使用RSpec而不是minitest测试来学习RSpec。当他创建关系测试时,我来到last chapter。如何使用Rails上的多个关联模型生成FactoryGirl关联?
型号:
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
这里是他MINITEST版本(工程):
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
工厂?