生成用于自定义active_storage验证的适当 Minitest

Generating proper Minitest for custom active_storage validation

提问人:Jerome 提问时间:11/14/2023 更新时间:11/14/2023 访问量:20

问:

以下类 (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

导致以下需要验证的类...和测试。

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
  [...]

如何编写一个通常会调用附件的测试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

没有所有相关数据进行验证?

通常情况下,参数记录为:

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"}

注意:我意识到我正在将其作为控制器测试运行。
a) 我很想在控制器操作中测试这一点,b
) 这些属性也可以成为模型测试的主题。但是如何正确调用类呢?

Ruby-on-Rails 小型测试 Rails-ActiveStorage

评论


答: 暂无答案