私は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
を生成するにはどうすればよいですか?