LoginSignup
2
2

More than 3 years have passed since last update.

Formオブジェクトを使用した際の単体テスト(FactoryBot)

Last updated at Posted at 2021-03-03

Formオブジェクトを使用した場合のテストコードを記述した際に、
何度もエラーが出てしまった部分を、忘れないように記録します。

フリマアプリで商品購入機能を実装し、その時のテストコードの一部になります。
以下がその一部です。

qiita.rb

   before do
    @user = FactoryBot.create(:user)
    @item = FactoryBot.build(:item)
    @item.image = fixture_file_upload('app/assets/images/test_image.jpeg')
    @item.save
    @order_purchaser = FactoryBot.build(:order_purchaser, user_id: @user.id, item_id: @item.id)

  end

@itemの部分でbuildアクションを使用しているのは、その後の記述で画像情報を@itemに追加するためで、
createアクションで定義してしまうとデータが保存され、後からの記述で追加ができなかったためです。

qiita.rb

 @order_purchaser = FactoryBot.build(:order_purchaser, user_id: @user.id, item_id: @item.id)

今回のフリマアプリで扱った購入者情報(@order_purchaser)は、user、itemに紐づいているため、カッコ内の記述で、user_id、item_idのデータを使用できるようにしています。

今回のコードが必要になったのは、Formオブジェクトを使用しており、モデル間のアソシエーションが記述されておらず、FactoryBotでassociationを組めなかった為です。

不足箇所や間違えているところがあれば、随時更新します。

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