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?

More than 1 year has passed since last update.

ActiveStorage(画像添付機能)を用いた際の単体テストコードの注意点

Posted at

はじめに

Activestorageを用いているアプリケーションで単体テストコードを書く際に、注意点が何点かあったため、忘れないために記録に残します。

注意点

1.FactoryBotでのimageカラムの取り扱いについて

fakerを使って、ランダムに画像データを添付させることは不可能なので、
あらかじめテスト用の画像データを用意しておく必要がある。

<対応策の一例>
1.「public」ディレクトリの中に「images」というディレクトリを作成し、画像「test.jpg」(任意)を、imagesディレクトリの中に配置する。

イメージ図(階層)
app
bin
・
・
public
  |
  images
     |
    test.jpg

2.afterというメソッドを用いて、インスタンス生成後に画像が保存されるようにする。

FactoryBot.define do
  factory :message do
    content {Faker::Lorem.sentence}
    association :user
    association :room

    after(:build) do |message|
      message.image.attach(io: File.open('public/images/test.jpg'), filename: 'test.jpg')
    end
  end
end

※:messageがbuildされた後で、io: File.openで設定したパスのファイル(public/images/test.jpg)を、test.jpgというファイル名で保存をしている。という意味。

2.単体テストコードを書く際の空の表現方法

nameなどの文字列
@hoge.name = ""

画像データなど
@hoge.image = nil
(""では空の文字列を保存という意味になると思われる)

3.補足情報

上記1で記載したfactorybotで、messageはuser,roomと必ず紐づいている必要があるため、

association :user
association :room

アソシエーションが追記されている。
これにより、messageが生成されたとき、それに紐づくuser,roomが自動生成される。

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?