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
工廠?