1
1

More than 3 years have passed since last update.

FactoryBotのアソシエーション

Last updated at Posted at 2021-04-17
terminal
Failures:

  1) Item#create image,item_name,description,category_id,status_id,prefecture_id,delivery_fee_payment_id,delivery_prepare_id,priceの値が存在すれば登録できること
     Failure/Error: expect(@item).to be_valid
       expected #<Item id: nil, item_name: "b21ywo", description: "frec268o37r2ulb917hgti5vwbf7hbt07sxp05ezpt8ad2z1iv...", category_id: 2, status_id: 4, delivery_fee_payment_id: 2, prefecture_id: 44, delivery_prepare_id: 4, price: 4723291, user_id: nil, created_at: nil, updated_at: nil> to be valid, but got errors: User must exist
     # ./spec/models/item_spec.rb:11:in `block (3 levels) in <top (required)>'

エラー文[but got errors: User must exist]とは

ユーザー情報がないよっといっています。

解説

条件 モデル名 組んでいるアソシエション 外部キー
①アソシエーション user has_many :item なし
②外部キーを保持 item belongs_to :user あり

解答

上記の中でitemモデルのテストを行う場合は外部キーを保持しているモデルのテストのファクトリーボットにアソシえーション設定が必要になってきます。

ruby
FactoryBot.define do
  factory :item do
    # image { Rack::Test::UploadedFile.new("#{Rails.root}/spec/fixtures/20210327-085606.png") }
    item_name {Faker::Lorem.characters(number: 6, min_alpha: 1, min_numeric: 1) }
    description {Faker::Lorem.characters(number: 100, min_alpha: 1, min_numeric: 1) }
    category_id {Faker::Number.between(from: 2, to: 11)} # 2〜11のいずれかがランダムに表示
    status_id {Faker::Number.between(from: 2, to: 6)} # 2〜6がランダムに表示
    prefecture_id {Faker::Number.between(from: 2, to: 48)} # 2〜48がランダムに表示
    delivery_fee_payment_id {Faker::Number.between(from: 2, to: 3)} # 2〜3がランダムに表示
    delivery_prepare_id {Faker::Number.between(from: 2, to: 4)} # 2〜4のいずれかがランダムに表示
    price {Faker::Number.between(from: 1, to: 9999999)} # 1〜9999999のいずれかがランダムに表示
    association :user
  end
end
1
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
1
1