简体   繁体   English

Rails单元测试模型验证:包含失败

[英]Rails unit testing model validation :inclusion fails

Model order.rb 模型order.rb

class Order < ActiveRecord::Base
    attr_accessible :address, :email, :name, :payment_type_id
    belongs_to :payment_type

    PAYMENT_TYPES = PaymentType.pluck(:id)

    validates :name, :address, :email, :payment_type_id, :presence => true
    validates :payment_type_id, :inclusion => {:in => PAYMENT_TYPES}
end

Model payment_type.rb 型号payment_type.rb

class PaymentType < ActiveRecord::Base
  attr_accessible :name, :id

  has_many :order
end

From browser, validation works fine, if it is wrong it give an error, else go forward. 在浏览器中,验证工作正常,如果输入错误,则会出错,否则继续进行。 But problem is when I run rake test:functionals from terminal. 但是问题是当我从终端运行rake test:functionals时。 Test didn't pass the validation. 测试未通过验证。 If I comment this line: 如果我对此行发表评论:

validates :payment_type_id, :inclusion => {:in => PAYMENT_TYPES}

all is ok. 一切都很好。 I don't understand why it is working in one plase, but in tests not ? 我不明白为什么它能一劳永逸,但在测试中却行不通? ... ...

Fixtures are all ok. 夹具都可以。

Please help. 请帮忙。

Most likely the problem is, that you are storing your payment types in a constant. 最可能的问题是,您将付款类型存储在一个常量中。

For your tests to work, the PaymentTypes have to be available in the database before rails loads your Order model, and this might not be the case. 为了使测试正常进行,在Rails加载Order模型之前,数据库中必须有PaymentTypes ,而事实并非如此。

One way to get around this, would be to use a (memoized) class method to store your payment types. 解决此问题的一种方法是使用(存储的)类方法存储您的付款类型。 As long as you access this class method after all your PaymentTypes are in the database, you should be fine. 只要在所有PaymentTypes都存储在数据库中之后访问此类方法,就可以了。

class Order < ActiveRecord::Base
  validates :payment_type_id, :inclusion => { :in => self.payment_types }

  def self.payment_types
    @@payment_types ||= PaymentType.pluck(:id)
  end
end

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

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