6
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

FactoryBotで関連モデルも一緒に生成する

Last updated at Posted at 2019-06-24

FactoryBot でテストデータを作成する際に関連付くモデルも一緒に生成する方法です。
呼び出し元の factory で after(:create) コールバックを使います。

参考記事

Factory Girl Callbacks
https://thoughtbot.com/blog/aint-no-calla-back-girl

準備

用意するモデル(1 対多の関連付け)

  • Post モデル
  • Comment モデル
$ bundle exec rails g model Post title body:text
Running via Spring preloader in process xxxxx
      invoke  active_record
      create    db/migrate/xxxxxxxxxxxxxx_create_posts.rb
      create    app/models/post.rb
      invoke    rspec
      create      spec/models/post_spec.rb
      invoke      factory_bot
      create        spec/factories/posts.rb

$ bundle exec rails g model Comment post:references content
Running via Spring preloader in process xxxxx
      invoke  active_record
      create    db/migrate/xxxxxxxxxxxxxx_create_comments.rb
      create    app/models/comment.rb
      invoke    rspec
      create      spec/models/comment_spec.rb
      invoke      factory_bot
      create        spec/factories/comments.rb

$ bundle exec rails db:migrate
app/models/post.rb
class Post < ApplicationRecord
  has_many :comments
end
app/models/comment.rb
class Comment < ApplicationRecord
  belongs_to :post
end

実装方法

以下のように記述することで、post に関連付く comment を作成することができます。

spec/factories/posts.rb
FactoryBot.define do
  factory :post do
    title { 'Test Title' }
    body { 'Test Body' }

    factory :post_with_comment do
      after(:create) do | post |
        create(:comment, post: post)
        # 5.times { create(:comment, post: post) }
      end
    end
  end
end
spec/factories/comments.rb
FactoryBot.define do
  factory :comment do
    association :post, factory: :post
    content { 'Test Content' }
  end
end

spec には以下のように書きます。

let!(:post) { FactoryBot.create(:post_with_comment) }

これで関連付くモデルも作成することができます。
下記は binding.irb で post に紐付く comment を確認した内容になります。

irb(#<RSpec::xxx>):001:0> post.comments
=> #<ActiveRecord::Associations::CollectionProxy [#<Comment id: 1, post_id: 1, content: "Test Content", created_at: "2000-01-01 00:00:00", updated_at: "2000-01-01 00:00:00">]>

以上です。

6
2
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
6
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?