Image upload using CarrierWave ~ Rspec test ~

Reference material

carrierwaveuploader/carrierwave

Rspec using CarrierWave for uploading multiple images-Qiita

[Rails] Introduction of carrierwave and MiniMagick when you want to save multiple images --Qiita

Introduction

gem 'carrierwave', '~> 2.0'

Create uploader after bundle install

be rails g uploader Images

app / uploaders / images_uploader.rb is created.

contents

class ImagesUploader < CarrierWave::Uploader::Base
  # Include RMagick or MiniMagick support:
  # include CarrierWave::RMagick
  # include CarrierWave::MiniMagick

  # Choose what kind of storage to use for this uploader:
  storage :file
  # storage :fog

  # Override the directory where uploaded files will be stored.
  # This is a sensible default for uploaders that are meant to be mounted:
  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

  # Provide a default URL as a default if there hasn't been a file uploaded:
  # def default_url(*args)
  #   # For Rails 3.1+ asset pipeline compatibility:
  #   # ActionController::Base.helpers.asset_path("fallback/" + [version_name, "default.png "].compact.join('_'))
  #
  #   "/images/fallback/" + [version_name, "default.png "].compact.join('_')
  # end

  # Process files as they are uploaded:
  # process scale: [200, 300]
  #
  # def scale(width, height)
  #   # do something
  # end

  # Create different versions of your uploaded files:
  # version :thumb do
  #   process resize_to_fit: [50, 50]
  # end

  # Add a white list of extensions which are allowed to be uploaded.
  # For images you might use something like this:
  # def extension_whitelist
  #   %w(jpg jpeg gif png)
  # end

  # Override the filename of the uploaded files:
  # Avoid using model.id or version_name here, see uploader/store.rb for details.
  # def filename
  #   "something.jpg " if original_filename
  # end
end

Added images column to Image table. (Already linked with the Post table when creating the Image table)

When uploading multiple files, it seems to be saved in json format, so specify it.

be rails g migration add_images_to_image images:json

migrate contents

class AddImagesToImage < ActiveRecord::Migration[6.0]
  def change
    add_column :images, :images, :json
  end
end

Rails db: migrate to add columns

Test implementation

models/image.rb

class Image < ApplicationRecord
  belongs_to :post
  validates :images, presence: true

  mount_uploaders :images, ImagesUploader
end

spec/factories/images.rb

FactoryBot.define do
  factory :image do
    images { [ Rack::Test::UploadedFile.new(Rails.root.join('spec/fixtures/test.jpg'), 'spec/fixtures/test.jpg') ] }
    post
  end
end

Create a fixtures directory under the spec directory. I created test.jpg in a pseudo manner.

spec/models/images.rb

require "rails_helper"

RSpec.describe Image, type: :model do
  let(:pic_path) { Rails.root.join('spec/fixtures/test.jpg') }
  let(:pic) { Rack::Test::UploadedFile.new(pic_path) }

  context "If an image is specified" do
    it "Image is uploaded" do
      image = create(:image)
      expect(image).to be_valid
    end

    it "image(Multiple)But uploaded" do
      image = create(:image, images: [pic, pic])
      binding.pry
      expect(image).to be_valid
    end
  end

  context "If no image is specified" do
    it "Get an error" do
      image = build(:image, images: nil)
      expect(image).to be_invalid
      expect(image.errors.messages[:images]).to eq ["can't be blank"]
    end
  end
end

Recommended Posts

Image upload using CarrierWave ~ Rspec test ~
Multiple image upload function using Rails Carrierwave
[Rails] Test code using Rspec
How to erase test image after running Rspec test with CarrierWave
Image upload
[RSpec] Unit test (using gem: factory_bot)
[Rails] How to upload images using Carrierwave
[Java] Test S3 upload / download using "S3 ninja"
[Rails] How to upload multiple images using Carrierwave
[RSpec] I wrote a test for uploading a profile image.
RSpec test code execution
CarrierWave Upload multiple images
[Rails] Test of star evaluation function using Raty [Rspec]
Introduction to RSpec 1. Test, RSpec
[Rails / RSpec] Write Model test (using Shoulda Matchers / FactoryBot)
[Rails] Test with RSpec
Test Nokogiri with Rspec.
[RSpec] Use WebMock to test logic using an external API
I'm writing test code using RSpec, but it doesn't work
[Rails] Save images using carrierwave
Test Active Strage with RSpec
Unit test architecture using ArchUnit
Test GraphQL resolver with rspec
[Rails] About Rspec response test
[Rails] How to upload images to AWS S3 using Carrierwave and fog-aws
How to implement UI automated test using image comparison in Selenium