2017-03-17 4 views
0

私はMichael Hartlのチュートリアルをやっていますが、RSpecを学ぶための最小テストの代わりに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の値がまだ存在しないため、エラーが発生しているようです。

工場の少女中関係について、あなたはちょうどこのようにそれを書くことができます:

あなたはこの新たな関係のためのユーザーインスタンスを作成します create(:relationship) FactoryGirlを呼び出すたび
FactoryGirl.define do 
    factory :relationship do 
    follower 
    followed 
    end 
end 

関連する問題