[RAILS] Memorandum (task: model test code)

I forgot the model test code with the image file, so I will output it.

Create an images directory in the public directory to place test images in your application files

Place images in the created images directory Example: (public/images/test image file)

class Item < ApplicationRecord
  belongs_to :user
  has_one_attached :image

abridgement
  validates :image, presence: true
end

validates seemed to be good with presence: true.

Write a description to open the image in the corresponding factories directory

after method

A specified process can be executed after any process By doing after (: build), you can execute the specified process after the instance is built.

FactoryBot.define do
  factory :item do
    
abridgement

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

# io: File.File with the path set by open (public/images/test_image.png), test_image.Save as png file name

How to write in the file that describes the test code (item_spec.rb file this time)

abridgement
      it 'Cannot be saved if name is empty' do
        @item.name = ''
        @item.valid?
        expect(@item.errors.full_messages).to include("Name can't be blank")
      end
      it 'Cannot be saved without the product image' do
        @item.image = nil #← When using Active Storage""If so, an error will occur, so use nil to create a blank.
        @item.valid?
        expect(@item.errors.full_messages).to include("Image can't be blank")
      end

abridgement

Until now, it was unified with "", but I learned from this test code. I think there are other ways to apply validation and write test code, but for the time being, the test code has turned green, so it seems to be working.

Recommended Posts

Memorandum (task: model test code)
RSpec ~ Task model validation test creation
[Rails] Unit test code for User model
What is the model test code testing
Efficient test code
Model unit test code to check uniqueness constraints
RSpec test code execution
[Test code learning / output]
Java test code method collection
[Rails] Test code using Rspec
Implementation of unit test code
Password dummy data generation notes in Rails model unit test code
A memorandum for writing beautiful code
Write test code in Spring Boot
[RSpec] How to write test code
[Rspec] Flow from introducing Rspec to writing unit test code for a model