LoginSignup
1
0

More than 3 years have passed since last update.

FactoryBotで忘れがちなことfor Ruby on Rails

Last updated at Posted at 2020-03-12

よくやります

Aに関連するユーザーを生成する。
関連付けでassociation :userで設定していると、ついついあることを忘れてしまい、そのユーザー所有のAを作成できない。

駄目なところの説明

FactoryBot.createでテストデータを作成するとき、FactoryBotのdefaultで作成させている。
これを実行すると、campaignが先に作成されてcampaignで関連付けしたuserのIDは1になる。
その後に、userが作成されるので、userのIDは2になる。
campaignをcreateしたときに、userを作っているので正しい動きですね。

spec/factories/users.rb
FactoryBot.define do
  factory :user, aliases: [:owner] do
    name 'MyString'
    sequence(:email) { |n| "tester#{n}@example.com" }
    password 'MyString'
    remember_digest 'MyString'
    admin true
  end
end
spec/factories/campaigns.rb
FactoryBot.define do
  factory :campaign do
    name "MyString"
    association :owner
    status 0
    start_date Date.today
  end
end
spec/features/campaigns_spec.rb
require 'rails_helper'

RSpec.feature "Campaigns", type: :feature do
  let(:user) { FactoryBot.create(:user) }
  let!(:campaign) { FactoryBot.create(:campaign) }

  scenario "Campaign list" do

    puts "This note's user is #{user.inspect}"
    puts "This note's campaign is #{campaign.inspect}"
  end
end

駄目なところのログ

campaignのuser_id: 1でuserのUser id: 2というのが確認できる。

This note's user is #<User id: 2, name: "MyString", email: "tester2@example.com", password_digest: "$2a$04$WonV91JKr29eOLQZAVnHm.7Dh3hkpvkbWEBe.uyxN4a...", admin: true, created_at: "2020-03-12 03:50:45", updated_at: "2020-03-12 03:50:45", remember_digest: "MyString">
This note's campaign is #<Campaign id: 1, name: "MyString", user_id: 1, status: 0, start_date: "2020-03-12", created_at: "2020-03-12 03:50:45", updated_at: "2020-03-12 03:50:45">

どちらもID1にするように直す

これを、以下のように変更する。
これを実行すると、userを先に作成してuserのIDは1になる。
そのuserのIDを使ってcampaignを作成してくれる。

  let!(:campaign) { FactoryBot.create(:campaign, user_id: user.id) }

直したあとのログ

campaignのuser_id: 1でuserのUser id: 1というのが確認できる。

This note's user is #<User id: 1, name: "MyString", email: "tester1@example.com", password_digest: "$2a$04$gP.QxECesAUpD41z9KLqw.ZnYBbXppVDv2FgurFEd2o...", admin: true, created_at: "2020-03-12 04:01:37", updated_at: "2020-03-12 04:01:37", remember_digest: "MyString">
This note's campaign is #<Campaign id: 1, name: "MyString", user_id: 1, status: 0, start_date: "2020-03-12", created_at: "2020-03-12 04:01:37", updated_at: "2020-03-12 04:01:37">

P.S.

他に良い方法があればご指南ください。

1
0
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
1
0