Cannot set required boolean attribute to false inside a Factory

1404 views
Skip to first unread message

Chris Bloom

unread,
Jun 27, 2011, 4:39:34 AM6/27/11
to factory_girl
It appears that when one has a *required* boolean attribute field, one
is unable to set that value to `false` through FactoryGirl, as FG
seems to think that means "don't set it"

# app/models/news_article.rb
class NewsArticle < ActiveRecord::Base
attr_accessible :title, :content, :published_at, :published

# ...

validates :published,
:presence => true
end

# spec/factories.rb
Factory.define :news_article do |f|
# ...
f.published true
end

# spec/models/news_article_spec.rb
describe NewsArticle do
describe "default scope" do
before do
NewsArticle.delete_all

t = Time.local(2004, 02, 25, 13, 30, 0)
Timecop.freeze(t)

@published_in_30_days = Factory(:news_article, :published_at
=> (Date.today + 30), :published => true)
@unpublished_in_31_days = Factory(:news_article, :published_at
=> (Date.today + 31), :published => false)
end

it "should only show published articles with published_at dates in
the past" do
# ...
end
end
end

# After running `rspec spec/` from Terminal
NewsArticle default scope should only show published articles with
published_at dates in the past
Failure/Error: @unpublished_in_31_days =
Factory(:news_article, :published_at => (Date.today + 31), :published
=> false)
ActiveRecord::RecordInvalid:
Validation failed: Published can't be blank

Chris Bloom

unread,
Jun 27, 2011, 10:33:16 AM6/27/11
to factory_girl
Crap. Nevermind. I missed the note on
http://ar.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html#M000083
about validating boolean fields.

Mauro Asprea

unread,
Feb 15, 2013, 6:33:50 AM2/15/13
to factor...@googlegroups.com, chris...@gmail.com
Take a look at ths SO Question http://stackoverflow.com/a/10506648/53720 for more info becuse the link is dead

If you want to validate the presence of a boolean field (where the real values are true and false), you will want to use validates_inclusion_of :field_name, :in => [true, false] This is due to the way Object#blank? handles boolean values. false.blank? # => true

Or in Rails3 way

validates :field, :inclusion => {:in => [true, false]}
Reply all
Reply to author
Forward
0 new messages