Home>

[What I want to achieve]
I want to use RSpec to implement validation tests when posting images

[Current status/related code]

  • Use ActiveStorage for posting images
  • Validation was set in the model so that images would not be posted when trying to post with a file size of 8MB or more.

models/Product.rb

validate: validate_image
def validate_image
   return unless image.attached?
   if image.blob.byte_size>8.megabytes
    image.purge
    errors.add (: image,'Please keep one file within 8MB')
   end
end

models/product_spec.rb

#frozen_string_literal: true
require'rails_helper'
RSpec.describe Product do
  describe'#create' do
File size of # 8MB or more is invalid.
    it'is invalid with a file size of 8MB or more'do
      @product = create (: product)
      @ product.image = fixture_file_upload ("/files/test_image.jpg")
      expect (@product) .not_to be_valid
    end
  end
end

I have a sample image of 8MB or more ("/files/test_image.jpg") stored in spec/fixtures/files, and I call it during the test so that a validation error will occur.

[Errors that appear]

Failures:
  1) Product # create is invalid with a file size of 8MB or more
     Failure/Error: image.purge
     FrozenError:
       can't modify frozen Hash
     # ./app/models/product.rb:17: in `validate_image'
     # ./spec/models/product_spec.rb:17: in `block (3 levels) in<main>'
Failed examples:
rspec ./spec/models/product_spec.rb:14 #Product # create is invalid with a file size of 8MB or more

When I checked the above error,

I get an error because I am trying to change the object even though I cannot change the contents of the object. If there is a way to release freeze, it will be solved

However, I don't know how to deal with it, so I would appreciate any advice on how to deal with this error.

  • Answer # 1

    https://qiita.com/mishiwata1015/items/f63a47098d0642dc3219

    Refer to the above article and

    models/product.rb

    def validate_image
       return unless image.attached?
       if image.blob.byte_size>8.megabytes
        Avoid by nil setting instead of calling image = nil #purge
        errors.add (: image,'Please keep one file within 8MB')
       end
      end

    After making this change, the test passed successfully