LoginSignup
8
2

More than 3 years have passed since last update.

FactoryBot ActiveStorageを使った画像を紐付ける方法

Posted at

FactoryBotとは

RSpecにテストを効率化するための機能です。
予め値を設定しておき、それに沿ったインスタンスを生成します。

ActiveStorageで画像を紐付けよう

factories/post.rb
FactoryBot.define do
  factory :post do
    #{ } の値が参照されて保存される。
    text {"テキストです"}

    #afterメソッド。Postインスタンスをbuildした後、画像をつける。
    after(:build) do |post|
      post.image.attach(io: File.open('spec/fixtures/test_image.png'), filename: 'test_image.png', content_type: 'image/png')
    end

  end
end

Postインスタンスのimageカラムに画像をつけるよう記述します。
HTTPリクエスト経由で画像を付けない場合は、

io: File.open('画像ファイル場所指定'), filename: 'ファイルの名前', content_type: 'ファイルのタイプ(imageとかtextとか)/拡張子

と記述します。

以上です!

8
2
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
8
2