繁体   English   中英

Hartl Ruby on Rails教程第11章测试问题:错误消息填满控制台

[英]Hartl Ruby on Rails tutorial Chapter 11 test issue: error message filling up console

我已经完成了有关Micropost Images的章节。 问题出现在第11.4节之后,当我运行bundle exec rake test出现7个错误。 我的控制台将以下行一直打印到控制台顶部:

app/models/micropost.rb:13:in `picture_size'
app/models/micropost.rb:13:in `picture_size'
app/models/micropost.rb:13:in `picture_size'
app/models/micropost.rb:13:in `picture_size'
app/models/micropost.rb:13:in `picture_size'
app/models/micropost.rb:13:in `picture_size'
app/models/micropost.rb:13:in `picture_size'
app/models/micropost.rb:13:in `picture_size'
app/models/micropost.rb:13:in `picture_size'
app/models/micropost.rb:13:in `picture_size'

你明白了。 这很头疼,因为我什至无法浏览控制台来弄清楚自己做错了什么或如何解决。 如果相关,下面是app / models / 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 :content, presence: true, length: { maximum: 140 }
  validate :picture_size

  private

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

我的问题是如何阻止app/models/micropost.rb:13:in picture_size'`打印出恶作剧并填满控制台?

您的picture_size方法是递归的,会创建一个无限循环-它将自己调用,它将无限执行。

if picture_size > 5.megabytes是罪魁祸首,它将调用在其中定义的方法。如果该行正确,则应重命名实际的验证方法,例如, validate :picture_under_size_limitdef picture_under_size_limit

if picture_size > 5.megabytes 

应该

if picture.size > 5.megabytes

注意. 而不是_

我自己犯了这个错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM