无法使用图片验证存在 Rails 5.x

Can't Use Validates Presence On Picture Rails 5.x

micropost.rb

class Micropost < ActiveRecord::Base
  belongs_to :user
  default_scope -> { order(created_at: :desc) }
  mount_uploader :picture, PictureUploader
  validates :user_id, presence: true
  validates :tag1, presence: true, length: { maximum: 20 }
  validates :tag2, presence: true, length: { maximum: 20 }
  validates :tag3, presence: true, length: { maximum: 20 }
  validates :picture, presence: true
  validate  :picture_size
  validates :ispublic, inclusion: { in: [ true, false ] } 

  private

    # Validates the size of an uploaded picture.
   def picture_size
     if picture.size > 5.megabytes
       errors.add(:picture, "should be less than 5MB in size.")
     end
   end
end

microposts_controller.rb 片段:

def create
  @micropost = current_user.microposts.build(micropost_params)
  if @micropost.save!
    flash[:success] = "Post created!"
    redirect_to root_url
  else
    @feed_items = []
    render 'static_pages/home'
  end
end

def micropost_params
    params.require(:micropost).permit(:tag1, :tag2, :tag3, :picture, :ispublic)
end

测试失败的片段:

tag1 = "This"
tag2 = "Is"
tag3 = "Sparta"
image = File.open("test/fixtures/p_avatar.png")
assert_difference 'Micropost.count', 1 do
  post microposts_path, params: {micropost: { tag1: tag1, tag2: tag2, tag3: tag3, picture: "image", 
  ispublic: false }}
end

测试错误:

Validation failed. Picture can't be blank.

我正在使用 CarrierWave...based on other answers 我想知道我是否不能对图片使用 presence: true 验证,但我认为 @micropost.save 会存储任何内容作为字符串 (varchar)。出于测试目的,我只想确保传递了一个有效的字符串,但如果 CarrierWave 和 picture_size 验证就足够了,也许这甚至没有必要。

找到了。在 Rails 规范中,有一个名为 fixture_file_upload() 的函数,它完成了为我创建图像对象(似乎是某种上传到缓存)并制作 Model.save() 方法对其进行验证并将字符串存储在数据库中。

多亏了这个网站,它告诉我一些关于不通过 FactoryBot 的图像上传测试的信息:https://jeffkreeftmeijer.com/carrierwave-rails-test-fixtures/

最终我决定我的微博 不需要 图片(A la Twitter)。