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?

factory_botインスタンスを作成するコマンド

Last updated at Posted at 2025-01-24

Build strategies

buildcreateattributes_forそしてbuild_stubbedというfactory_botはいくつかの異なるビルド戦略を持っています。

factory_bot supports several different build strategies: build, create, attributes_for and build_stubbed:

# 保存されないUserモデルインスタンスを返します
# Returns a User instance that's not saved
user = build(:user)

# 保存されるUserインスタンスを返す
# Returns a saved User instance
user = create(:user)

# 例えばUserインスタンスをビルドするために使用する属性のハッシュを返します
# Returns a hash of attributes, which can be used to build a User instance for example
attrs = attributes_for(:user) # モデル名を入れることで構成する属性のハッシュが返される

# パターン一致割り当てとruby3.0のサポートで統合する
# Integrates with Ruby 3.0's support for pattern matching assignment
attributes_for(:user) => {email:, name:, **attrs} # **この部分で統合されるのだろう

# 定義されたすべての属性を消したオブジェクトが返ってくる
# Returns an object with all defined attributes stubbed out
stub = build_stubbed(:user)

# 上のメソッドのどれかにブロックを渡すことは以下のオブジェクトが返される
# Passing a block to any of the methods above will yield the return object
create(:user) do |user|
  user.posts.create(attributes_for(:post)) # ブロックでさらに複雑な生成ができるようだ
end

build_stubbedMarshal.dump

build_stubbed and Marshal.dump

build_stubbedで作成されたオブジェクトはMarshal.dumpでシリアライズ化されないことに注意して下さい。factory_botはこれらのオブジェクトにシングルトンメソッドを定義しているからです

Note that objects created with build_stubbed cannot be serialized with Marshal.dump, since factory_bot defines singleton methods on these objects.

感想

生成する際の手法を戦略敵にやるからストラテジーと呼ぶのかな

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?