2017-03-17 88 views
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工廠?

回答

0

這似乎是因爲這些用戶仍然不存在,你硬編碼follower_idfollowed_id值引發錯誤。

對於工廠女孩的關係,你可以只寫它:

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

每當你打電話create(:relationship) FactoryGirl將創建用戶實例爲這種新關係。