Hi, class B < ActiveRecord::Base belongs_to :a validates_numericality_of :some_attribute, :greater_than => 0, :allow_blank=>true def some_attribute a.numeric_attr * read_attribute(:some_attribute) end ... If I create an instance of my class B in rspec with factory_girl w.out a parent (but not required!) instance of class A, I get the following error: "undefined method `numeric_attr'' for nil:NilClass". Why? Is this an apparent idiosyncrasy of using rspec and factory_girl together? Thanks, Lille
David Chelimsky
2010-Jul-26 17:06 UTC
[rspec-users] [newbie] rspec, validations and factory_girl
On Jul 26, 2010, at 11:34 AM, Lille wrote:> Hi, > > class B < ActiveRecord::Base > belongs_to :a > validates_numericality_of :some_attribute, :greater_than => > 0, :allow_blank=>true > > def some_attribute > a.numeric_attr * read_attribute(:some_attribute) > end > ... > > If I create an instance of my class B in rspec with factory_girl w.out > a parent (but not required!)It may not be a business requirement, but the some_attribute method above requires it''s existence in order to run without error. Try: def some_attribute return nil unless a a.numeric_attr * read_attribute(:some_attribute) end HTH, David> instance of class A, I get the following > error: "undefined method `numeric_attr'' for nil:NilClass". > > Why? Is this an apparent idiosyncrasy of using rspec and factory_girl > together? > Thanks, > > Lille
OK. On a Rails note, this seems to suggest that attributes are checked from their accessors before the save, whereas I had assumed my some_attribute accessor would not be called at all during validation... (Thank you David, this is one of the better groups I''ve lately monitored, and a fine complement to your book...) Thanks, Lille On Jul 26, 1:06?pm, David Chelimsky <dchelim... at gmail.com> wrote:> On Jul 26, 2010, at 11:34 AM, Lille wrote: > > > Hi, > > > class B < ActiveRecord::Base > > ?belongs_to :a > > ?validates_numericality_of :some_attribute, :greater_than => > > 0, :allow_blank=>true > > > ?def some_attribute > > ? ? ?a.numeric_attr * read_attribute(:some_attribute) > > ?end > > ?... > > > If I create an instance of my class B in rspec with factory_girl w.out > > a parent (but not required!) > > It may not be a business requirement, but the some_attribute method above requires it''s existence in order to run without error. > > Try: > > def some_attribute > ? return nil unless a > ? a.numeric_attr * read_attribute(:some_attribute) > end > > HTH, > David > > > instance of class A, I get the following > > error: "undefined method `numeric_attr'' for nil:NilClass". > > > Why? Is this an apparent idiosyncrasy of using rspec and factory_girl > > together? > > Thanks, > > > Lille > > _______________________________________________ > rspec-users mailing list > rspec-us... at rubyforge.orghttp://rubyforge.org/mailman/listinfo/rspec-users