LoginSignup
3
3

More than 3 years have passed since last update.

FactoryBotの記述についての備忘録

Last updated at Posted at 2020-01-10

まずFactoryBotの記述を簡略化するために
以下の記述をする。

spec/spec_helper.rb
#〜省略〜
RSpec.configure do |config|
  config.include FactoryBot::Syntax::Methods
  #RSpec~ の do~end内に上記の記述をする。
  #〜省略〜
end

下記の記述に関して他に応用が効くように公式化してみようと思う。

spec/factories/messages.rb
FactoryBot.define do
  factory :message do
    content {Faker::Lorem.sentence}
    image {File.open("#{Rails.root}/public/images/test_image.jpg")}
    user
    group
  end
end

公式化

spec/factories/message
FactoryBot.define do
# gem名.define do
  factory :message do
  #factry :モデル名 do                       以下で左記モデルのテストデータを定義する。
  #factry :テストデータ名, class モデル名 do     左記のような形だと、左記モデル内の"テストデータ名"というテストデータを定義する

    content {Faker::Lorem.sentence}
    # カラム名 {gem名::Lolem.表示形式}      カッコ内はFakerというgemの記法。Lolem はダミーテキストの1種で.sentenceはその表示形式(今回は文章として表示)
    # カラム名 '任意の文字列'                左記で任意の文字列を表示させることも可能
    image {File.open("#{Rails.root}/public/images/test_image.jpg")}
    # カラム名 {表示形式.open("写真のルート")}
    user
    group 
  end
end

現状の理解ではこのようなイメージ。
File.openのところや、Rails.rootのところ
FactoryBotの記述を簡略化するための記述に関する理解に自信がないので、
もし解釈が異なるところがありましたらご教示ください。

3
3
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
3
3