Sat, 09 Sep 06

In memory AR object for testing

I’ve previously written about using in memory active record objects for testing.

In doing so recently, I’ve found it necessary to define the id of the in memory object. By default this is obviously nil as it has not been persisted. In addition, it is not possible to set it during normal object construction.

person = Person.new(:id => 1)
p person.id
#=> nil

However, we can give the person constructor a block, setting the id just after creation.

person = Person.new { |p| p.id = 1 }
p person.id
#=> 1

Cool.