LoginSignup
0
0

More than 1 year has passed since last update.

fixture_file_uploadメソッドを使用してテストコードを書く

Posted at

Formオブジェクトを導入してテストコードにエラーが出た

テストコードを打ち込む際にエラーで悩まされていたのですが、Formオブジェクトを導入すると以下のように
fixture_file_uploadメソッドを使用しないと行けないという事が分からずに時間をかけてしまいました。
以前はafterメソッドを使用してダミー画像をFactoryBotで用意していたのですが

FactoryBot
after(:build) do |item|
  item.image.attach(io: File.open('public/images/test_image.png'), filename: 'test_image.png')
end

Formオブジェクトを導入すると上記の方法ではダミー画像を使用できませんでした。

fixture_file_uploadメソッド

調べてみると下記のようにRSpecにfixture_file_upload(該当ディレクトリの画像ファイル)を使用して
インスタンス変数に代入すると良いと言うことで試してみた所無事解決しました。

RSpec
RSpec.describe ItemForm, type: :model do
  before do
    user = FactoryBot.create(:user)
    @item = FactoryBot.build(:item_form, user_id: user.id)
    @item.image = fixture_file_upload('app/assets/images/abc.png')
    sleep(0.1)
  end
end

学んだこと

RSpecとFactoryBotについての関係性について改めて理解度を深める事が出来ました。

参考にさせて頂いたサイト

ActiveStorageとFakerを利用した際に、画像を含めたテストをする方法

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