FactoryBotメモ

『Everyday Rails - RSpecによるRailsテスト入門』を読んでRSpecを使い始めました。
以下メモ

ファクトリ

↓spec/factories/users.rb

FactoryBot.define do
  factory :user do
    name "マイク"
    text "こんにちわです"
    sequence(:email) { |n| "tester#{n}0@example.com" }
    password "dottle-nouveau-pavilion-tights-furze"
    
  end
end


↓spec/factories/blogs.rb

FactoryBot.define do
  factory :blog do
    title "サンプルブログ"
    text  "日記帳です。"
    association :user
   
 end
end


↓spec/factories/articles.rb

FactoryBot.define do
  factory :article do
    sequence(:title) { |n| "海に行きました #{n}" }
    text  "キレイでした。"
    association :blog

  end
end


実行コード

require 'rails_helper'

RSpec.feature "Articles", type: :feature do

 scenario "ファクトリの確認" do
    article = FactoryBot.create(:article)
    puts article.inspect

    puts article.blog.inspect

    puts article.blog.user.inspect
    
    other_article = FactoryBot.create(:article)
    puts other_article.inspect

    puts other_article.blog.inspect

    puts other_article.blog.user.inspect
 
  end
end


結果

#<Article id: 1, title: "海に行きました 1", text: "キレイでした。", blog_id: 1, created_at: "2018-10-16 03:22:33", updated_at: "2018-10-16 03:22:33">
#<Blog id: 1, title: "サンプルブログ", text: "日記帳です。", user_id: 4, created_at: "2018-10-16 03:22:33", updated_at: "2018-10-16 03:22:33">
#<User id: 4, email: "tester20@example.com", created_at: "2018-10-16 03:22:33", updated_at: "2018-10-16 03:22:33", name: "マイク", text: " こんにちわです", admin: false>
#<Article id: 2, title: "海に行きました 2", text: "キレイでした。", blog_id: 2, created_at: "2018-10-16 03:22:33", updated_at: "2018-10-16 03:22:33">
#<Blog id: 2, title: "サンプルブログ", text: "日記帳です。", user_id: 5, created_at: "2018-10-16 03:22:33", updated_at: "2018-10-16 03:22:33">
#<User id: 5, email: "tester30@example.com", created_at: "2018-10-16 03:22:33", updated_at: "2018-10-16 03:22:33", name: "マイク", text: " こんにちわです", admin: false>


  • ファクトリデータ同士で関連付けが出来ているので、FactoryBot.create(:article)だけで紐付いたblogとuserが作成される
  • 複数回作成すれば、紐付いたデータも作成した分だけ作られる
  • データの参照は例えばユーザーなら article.blog.user で可能


  • フィーチャースペックだけ実行したい場合は $ bin/rspec spec/features
  • スペックの作成方法は $ rails generate rspec:(スペックの種類) (スペック名)