I'm building a Rails application and I've encountered a really odd bug. The code [true false].sample
is never supposed to return blank. However, it sometimes does so when running rake db:seed
.
In my application I have a Store model that has presence validations:
class Store < ActiveRecord::Base
validates_presence_of :accepts_credit, :parking
end
I also run a test in rspec like this (that always passes)
require 'rails_helper'
RSpec.describe Store, type: :model do
it { should validate_presence_of :accepts_credit }
it { should validate_presence_of :parking }
end
Now, in my seeds file I have
Store.create(
...
accepts_credit: [false, true].sample(1),
parking: %w[lots some none].sample(1),
...
)
Running this in the terminal with rake db:reset --trace
, I get errors that the store wasn't created. I inspected this by running Store.create!
instead of Store.create
which causes the terminal to display errors.Validation failed: Accepts credit can't be blank
.
Now, I'm relatively new to Rails but I don't understand why the sample method .sample
could return blank. According to the docs: http://ruby-doc.org/core-2.2.0/Array.html#method-i-sample, sample always returns an element from the array.
Edit
I've used .sample
in replace of .sample(1)
as well.
What am I missing? Is .blank
doing what I think it is?