0
1

More than 3 years have passed since last update.

Railsチュートリアル 14章 FactoryBotでRelationshipのテストデータの作成

Posted at

はじめに

Railsチュートリアルをrspecに対応させながら取り組んでいたところ、14.2.3のリスト14.28のユーザのRelationshipテストデータをFactoryBotで作ろうとしたときにハマってしまったので、備忘録として投稿します。

環境

  • ruby 2.7.2
  • rails 6.0.3
  • factory_bot_rails 6.1.0
  • rspec-rails 4.0.1

やりたいこと

①下記ようにrelationshipのテストデータを作成するfixtureをFactoryBotで定義する。
②userのテストデータも同時にFactoryBotの定義内で作成する。

test/fixtures/relationships.yml(リスト14.28)
one:
  follower: michael
  followed: lana

two:
  follower: michael
  followed: malory

three:
  follower: lana
  followed: michael

four:
  follower: archer
  followed: michael

解決方法

試してみて、採用した解決方法を記載します。

その1 Relationshipのテストデータを作成するFactoryを定義(①のみ解決)

一番素直な方法です。follower_idとfollowed_idを持つRelationshipクラスのファクトリーを作成します。ただ、この方法でassociationをうまく設定することができなかったので、userのテストデータを別途作成しました。

spec/factories/relationships.rb
 factory :relationship, class: Relationship do
    follower_id { follower.id }
    followed_id { followed.id }
  end
spec/models/relationship_spec.rb
RSpec.describe Relationship, type: :model do
  let(:follower) { create(:user) }
  let(:followed) { create(:user) }
  let(:relationship) { create(:relationship, follower: follower, followed: followed) }

  it { expect(relationship).to be_valid }
end

その2 Relationshipを持つuserのテストデータを作成するFactoryBotを定義(①②の両方解決?)

2つめの方法は、Relationshipを持つuserのテストデータを作成する方法です。userのテストデータはすべてのテストでRelationshipを持っている必要はないので、traitで必要に応じて設定できるようにしています。この方法だと、userとrelationshipのテストデータをそれぞれ作成しなくても良くなりました。しかし、この方法はあくまでuserのテストデータを作成する方法で、relationshipを呼び出すにはuserを通す必要があるので、relationshipのテストには向いていなさそうです。

spec/factories/users.rb
factory :user do
  .
  .
  .
  trait :has_followed do
    after(:create) do |user|
      followed = create(:user)
      user.follow(followed) 
    end
  end
end
spec/models/relationship_spec.rb
RSpec.describe Relationship, type: :model do
  let(:user) { create(:user, :has_followed) }

  it { expect(user.actve_relationships).to be_valid }
end

終わりに

結局①②を完全に達成する解決方法を見つけられなかったので、relationshipのテストはその1の方法で、relationshipを持つuserのテストはその2で書くことにしました。

参考文献

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1