【发布时间】:2015-10-10 23:30:50
【问题描述】:
我正在构建一个 Rails 应用程序,但遇到了一个非常奇怪的错误。代码[true false].sample 永远不应该返回空白。但是,有时在运行rake db:seed 时会这样做。
在我的应用程序中,我有一个具有存在验证的 Store 模型:
class Store < ActiveRecord::Base
validates_presence_of :accepts_credit, :parking
end
我也像这样在 rspec 中运行测试(总是通过)
require 'rails_helper'
RSpec.describe Store, type: :model do
it { should validate_presence_of :accepts_credit }
it { should validate_presence_of :parking }
end
现在,在我的种子文件中,我有
Store.create(
...
accepts_credit: [false, true].sample(1),
parking: %w[lots some none].sample(1),
...
)
使用rake db:reset --trace 在终端中运行此程序,我收到未创建商店的错误。我通过运行Store.create! 而不是Store.create 对此进行了检查,这会导致终端显示错误。Validation failed: Accepts credit can't be blank。
现在,我对 Rails 比较陌生,但我不明白为什么示例方法 .sample 会返回空白。根据文档:http://ruby-doc.org/core-2.2.0/Array.html#method-i-sample,sample 总是从数组中返回一个元素。
编辑
我也用.sample 代替了.sample(1)。
我错过了什么? .blank 在做我认为的事情吗?
【问题讨论】:
标签: ruby-on-rails ruby rspec