0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[RSpec]createメソッドからブロック構文で囲って追いデータ作るやつ備忘録

Last updated at Posted at 2024-08-23

概要

letメソッドで定義したuser_...の変数だけ使いたい場合、関連オブジェクトのfavorite_...の定義がちょっと無駄だったりする。

let(:user_1) { create(:user, name: "ハム太郎") }
let(:favorite_1) { create(:favorite, user: user_1, name: "ヒマワリのタネ") }

let(:user_2) { create(:user, name: "まいどくん") }
let(:favorite_2) { create(:favorite, user: user_2, name: "おそうじ") }
let(:favorite_3) { create(:favorite, user: user_2, name: "お金もうけ") }

let(:user_3) { create(:user, name: "トラハムくん") }
let(:favorite_4) { create(:favorite, user: user_3, name: "スケボー") }
let(:favorite_5) { create(:favorite, user: user_3, name: "歌") }
let(:favorite_6) { create(:favorite, user: user_3, name: "ダンス") }

対応

基本

createメソッドでブロック構文を囲み関連オブジェクトのcreateを羅列することでスッキリ書く事ができる。

let(:user_1) {
  create(:user, name: "ハム太郎") do |user|
    create(:favorite, user:, name: "ヒマワリのタネ")
  end
}

let(:user_2) {
  create(:user, name: "まいどくん") do |user|
    create(:favorite, user:, name: "おそうじ")
    create(:favorite, user:, name: "お金もうけ")
  end
}

let(:user_3) {
  create(:user, name: "トラハムくん") do |user|
    create(:favorite, user:, name: "スケボー")
    create(:favorite, user:, name: "歌")
    create(:favorite, user:, name: "ダンス")
  end
}

応用

create_listメソッドでブロック構文を囲むと関連オブジェクト毎に何かできるようになる。

let(:user_4) {
  create(:user, name: "ヨクバリス") do |user|
    create_list(:favorite, 108, user:) do |favorite|
      # TODO: favoriteの数だけ何かできるかも?
    end
  end
}
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?