【问题标题】:Rails inclusion validation failureRails 包含验证失败
【发布时间】:2014-05-28 00:25:00
【问题描述】:

我的模型包含两个整数列,分别代表 start_timeend_time。这些时间由当天的分钟偏移量表示。

class Example < ActiveRecord::Base
    validates :start_time, inclusion: 0..1440
    validates :end_time,   inclusion: 0..1440
end

我也有工厂

FactoryGirl.define do
    factory :examples do
        start_time { Kernel.rand(1441) }
        end_time   { Kernel.rand(1441) }
    end
end

当我构建这个对象并检查它是否对 RSpec 有效时,我得到了与 start_time 和 end_time 不在列表中。检查对象的值表明它们在范围内。

我已经尝试了以下方法来让它工作。

inclusion: { in: 0..1440 }
inclusion: [0..1440].flatten

---编辑

在 RSpec 中

let(:example_klass) { FactoryGirl.build(:example) }
expect(example_klass).to be_valid ##=> FAILS

在 Rails 控制台中

t = FactoryGirl.build(:example)
t.valid?
=> true

任何帮助将不胜感激!

【问题讨论】:

  • 有一些bug,试试Random.rand(0..1440)
  • 我切换到Kernel.rand(1441)。错误仍然存​​在。
  • 您遇到了什么具体错误?我尝试了你的代码,它对我来说非常适合在 Rspec 中进行少量更正:'expect' 代码应该在 'it' 块中公开
  • 顺便说一句:你的 'FactoryGirl.build(:example)' 应该调用 factory :examples

标签: ruby-on-rails validation activerecord rspec


【解决方案1】:

使用

FactoryGirl.define do
    sequence :start_time , (0..1441) do |n|
        n   
    end
    sequence :end_time   , (0..1441) do |n|
        n   
    end 
end

在您的示例工厂中使用

FactoryGirl.define do
    factory :examples do
        start_time 
        end_time
    end
end

任何内容请参阅文档:https://github.com/thoughtbot/factory_girl/wiki/Usage#sequences-and-associations

希望对你有帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多