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?

ファクトリの名前と属性を設定する

Posted at

各ファクトリは名前と属性のセットを持ちます。名前がデフォルトによってオブジェクトのクラスを推測するために名前は使われます。

Each factory has a name and a set of attributes. The name is used to guess the class of the object by default:

ファクトリを生成する

# This will guess the User class
FactoryBot.define do # 名前と属性のセット オブジェクトのクラスを推測できる名前にする
  factory :user do # 名前
    first_name { "John" } # 属性
    last_name  { "Doe" }
    admin { false }
  end
end

クラスを明白に明示することが可能です

It is also possible to explicitly specify the class:
これはUserクラスを使うだろう(さもなければAdminが推測されるだろう)

# This will use the User class (otherwise Admin would have been guessed)
factory :admin, class: "User"

定数が使用可能な場合、さらに定数に渡すことができる(これは定数を参照はしきりに読み込間れるために大きなrailsアプリケーション内でテストパフォーマンス問題が引き起こされることに注意して下さい。)

You can pass a constant as well, if the constant is available (note that this can cause test performance problems in large Rails applications, since referring to the constant will cause it to be eagerly loaded).

factory :access_token, class: User

属性をハッシュとして設定する

rubyのブロック構文により、属性をハッシュとして定義する場合(例えばシリアライズ化されたもの/JSON属性) 中括弧のセットを二つ必要とする。

Because of the block syntax in Ruby, defining attributes as Hashes (for serialized/JSON columns, for example) requires two sets of curly brackets:

factory :program do
  configuration { { auto_resolve: false, auto_define: true } } # auto_resolve: false, auto_define: trueが二つのセット
end

代わりに do/end構文をより好無かもしれない:

Alternatively you may prefer do/end syntax:

factory :program do
  configuration do
    { auto_resolve: false, auto_define: true }
  end
end

ハッシュだと設定が複雑にある

しかし、ハッシュとして値の定義は オブジェクトを構築するときハッシュ内の値を設定することが複雑にする。それよりもfactory_bot自身を使うことを好む

However, defining a value as a hash makes it complicated to set values within the hash when constructing an object. Instead, prefer to use factory_bot itself:

factory :program do
  configuration { attributes_for(:configuration) } # 二つに分かれるから複雑に見える
end

factory :configuration do
  auto_resolve { false }
  auto_define { true }
end

簡単に属性値を設定できる

作るときにこの方法はより簡単に値を設定できます。

This way you can more easily set value when building:

create(
  :program, # 名前
  configuration: attributes_for( # 一つ見えることでシンプルになる
    :configuration,
    auto_resolve: true,
  )
)

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?