How to test including images when using ActiveStorage and Faker

【Overview】

1. Conclusion </ b>

2. Why use fixture_file_upload instead of creating an image in Faker </ b>

3. How to use </ b>

4. What I learned from here </ b>

  1. Conclusion

Use the fixture_file_upload </ b> method.


2. Why use fixture_file_upload instead of creating an image in Faker

There is one reason.

Since ActiveStorage is used, the image column is not created. Therefore, it cannot be created with Faker (even if a concrete image is inserted, it cannot be set because spec / factories does not have an image column).

Even if I was making an image column, I didn't know how to randomly generate (pick up) images with Faker. (No such feature was found on Github in Faker.)


3. How to use

The answer is simple, in the corresponding file in spec / models, Just assign fixture_file_upload (the image file in that directory) to your instance variable. (If you are programming a concrete example in spec / factories without using Faker, it will be a local variable)

spec/models


require 'rails_helper'

RSpec.describe BuyItem, type: :model do
  describe '#create' do
    before do

      @buy_item = FactoryBot.build(:buy_item)
      @buy_item.image = fixture_file_upload('app/assets/images/aiueo.png')

    end
  end
end

It will be like this! I haven't programmed a concrete example in spec / factories (I'm using Faker and there is no image column), so I put an appropriate concrete image directly into the instance variable. By doing so, the error "Image can't be blank" disappears because the image is put directly in "@buy_item".
5. What I learned from here (used in case of error)

Even though I am using the ActiveStorage gem, I made "image" in the ram name. Also, I didn't know how to make an image with Faker, so I deleted the column name. After that, as a result of various searches to assign an image to an instance variable without relying on Faker (appropriate image instead of random generation), I came to fixture_file_upload and was saved!

Reference URL: Test file upload using rspec-rails

Recommended Posts