Generating proper Minitest for custom active_storage validation

30 Views Asked by At

The following classes (Rails 7.0)

class Shop < ApplicationRecord
  has_one    :document_validation
end

class Union < ApplicationRecord
  belongs_to :shop
end

class Individual < ApplicationRecord
  belongs_to :shop
end

lead to the following class that requires validations... and testing.

Class Picture 
  has_one_attached :fichier
  belongs_to :individual, optional: true
  belongs_to :union, optional: true

  validate  :at_least_one_identifier
  validate  :fichier_size
  
  def at_least_one_identifier
    if [self.individual_id, self.union_id].reject(&:blank?).size == 0
      errors[:base] << (I18n.t('picture.one_identifier'))
    end
  end

  def fichier_size
    if fichier.attached? && self.individual_id
      limit = self.individual.shop
    elsif fichier.attached? && self.union_id
      limit = self.union.shop
    end

    if fichier.attached? && fichier.blob.byte_size > limit.document_validation.size_less_than
      fichier.purge
      errors[:base] << (I18n.t(attachments.too_big))
    elsif fichier.attached? && limit.document_validation.content_types.exclude?(fichier.blob.content_type)
      fichier.purge
      errors[:base] << (I18n.t(attachments.wrong_type))
    end
  [...]

How can one write a test which would normally invoke an attachment with fixture_file_upload

post pictures_url, params: { picture: { fichier: fixture_file_upload("space_cowboy.bmp", "image/bmp"),  
shop_id: shops(:one).id, individual_id: individuals(:one).id } }, xhr: true

without all relevant data to conduct the validation?

when normally params are logged as:

Processing by PicturesController#create as TURBO_STREAM
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"[FILTERED]", "picture"=>{"individual_id"=>"88", "fichier"=>#<ActionDispatch::Http::UploadedFile:0x00007f46d89fbcc8 @tempfile=#<Tempfile:/tmp/RackMultipart20231113-333814-gu934u.jpg>, @content_type="image/jpeg", @original_filename="Aleglise.jpg", @headers="Content-Disposition: form-data; name=\"picture[fichier]\"; filename=\"space_cowboy.jpg\"\r\nContent-Type: image/jpeg\r\n">}, "commit"=>"Create"}

note: i realise I am running this as a controller test.
a) I am curious to test this in a controller action and
b) these attributes could also be subject of a model test.. but the how to invoke the class properly?

0

There are 0 best solutions below